Pass Function to Method Prototype - c++

Say I have a template:
template <typename T>
class foo{
void (T::bar*)(int);
public:
void setMethod(void (T::*)(int) f)
};
Is there a way to use a non-member function with this template?
I've tried:
foo<void>().setMethod(&func);
foo<nullptr_t>().setMethod(&func);

No, it's not possible.
The precise nature of a useful workaround depends on the nature of the problem, but it'll most likely involve std::function and std::bind (or lambdas). In very general terms, the trick is usually to rewrite foo in such a manner that it does not have to care about the kind of function that is bound to it (which is what std::function is for).
One way this might be done is
template <typename T>
class foo{
public:
// Here we do not care about the type of function we're binding
template<typename Func>
void setMethod(Func f) { func_ = f; }
void callMethod(T &obj) { func_(obj); }
private:
// only about its signature
std::function<void(T&)> func_;
};
Given a type
struct A {
void foo();
void bar(int);
};
and a function
void qux(A &);
It is later possible to do any of
Foo<A> f;
f.setMethod(&A::foo);
f.setMethod(qux);
f.setMethod(std::bind(&A::bar, std::placeholders::_1, 2));
f.setMethod([](A &obj) { obj.foo(); });
Or indeed to call setMethod with anything that has an operator() accepting an A&.
In the event that Liskov substitution is required (which is the case for OP), this will not work because foo cannot offer an interface depending on the template arguments in a common base class. Then two options remain:
If the object the function is to be called on can be bound at the same time as the function, it is possible to make foo a class, have it store a std::function<void()> and shove a std::bind(&SomeClass::memberfunction, SomeObject) into it.
Otherwise, the best you're going to get without very evil hackery is limiting yourself to a common base class of what would have been T arguments to foo.
If your needs go beyond that, you're attempting to stretch the limits of the C++ type system and should probably reconsider your design.

Related

Same function with and without template

I am trying to understand a piece of code of C++11.
A class contains 2 functions as shown below:
class abc
{
public:
void integerA(int x);
template<typename typ>
void integerA(typ x);
};
I am unable to understand benefit of declaring 2 same functions. Why not declare only one template function?
Only one benefit I can assume is we know int data type which can be passed to this function. This might be little faster. But for this, do we really need to create a separate function with int data type?
The main reason to do something like this is to specialize void integerA(int x) to do something else. That is, if the programmer provides as input argument an int to member function abc::integerA then because of the C++ rules instead of instantiating the template member function the compiler would pick void integerA(int x) because concrete functions are preferred when possible instead of instantiating a template version.
A more straightforward way to do this would be to specialize the template member function in the following manner:
class abc
{
public:
template<typename typ>
void integerA(typ x);
};
template<typename typ>
void abc::integerA(typ x) {
...
}
template<>
void abc::integerA(int x) {
...
}
LIVE DEMO

Given a T and function name and type, how can I resolve T::function?

Given an Event struct and an object that implements a function with a specific name and prototype, known by the Event struct, I want to return a pointer or bind to that function. Exactly what it returns doesn't matter; it can just as easily be a pointer-to-member-function or a bind.
It's a bit hard to explain, so here's some psuedo-code:
struct Foo {
void onEvent();
};
struct Bar {
void onEvent();
};
struct Event
{
// I'm not sure what would go here
// Needs something that can be used to resolve T::onEvent, without
// knowing what T is until GetEventFunction is called.
typedef std::function<void()> function_type;
};
template<typename T, typename EventType>
EventType::function_type GetEventFunction(T* object)
{
return std::bind(T::(EventType::Something), object);
}
GetEventFunction<Foo, Event>(new Foo); // Returns Foo::onEvent
GetEventFunction<Bar, Event>(new Bar); // Returns Bar::onEvent
Can this behavior be achieved, or is C++ too limited to allow this?
Please read this before answering
I am not looking for reflection. As far as I'm aware, all of the information needed to do what I'm aiming for is available at compile time.
Also, I am not interested in alternate approaches. I know many ways to achieve this behavior with additional code, such as template specializations for each Event type, but I'm looking for a way to achieve this specifically.
Maybe I didn't explain well, but the function name is unique for each Event type. A FooEvent should resolve T::onFooEvent, while a BarEvent should resolve T::onBarEvent.
C++ can operate on types and values, but not on names. That's dealing with text, which is a macro-level thing that happens before C++ proper gets to look at the code. You can't take the type BarEvent and convert it into the function T::onBarEvent, because there is no association between them except for what they happen to be named.
That's why Luc's answer used a specific name: names of functions have to be hard-coded.
Now, you can side-step C++'s rules a bit via the use of a traits template. For example, you can create an event_traits template type that has a member function which takes T and calls a specific function on it. It would look like this:
template<typename event_type>
struct event_traits
{
template<typename T> void Dispatch(T *t) {t->DefaultEventFunction();}
};
The above uses DefaultEventFunction.
If you want each Event to have its own event function, you'll need a specialization for each Event class. And if you want to enforce this rule, simply never define DefaultEventFunction in any of your T objects; the compiler will complain. Change the name into something unlikely to be used, like WhyDidYouNameThisFunctionLikeThisStopIt.
template<>
struct event_traits<FooEvent>
{
template<typename T> void Dispatch(T *t) {t->onFooEvent();}
};
template<>
struct event_traits<BarEvent>
{
template<typename T> void Dispatch(T *t) {t->onBarEvent();}
};
This is where macros can come in handy:
#define REGISTER_EVENT_HANDLER(eventName)\
template<> struct event_traits<eventName>\
{\
template<typename T> void Dispatch(T *t) {t->on ## eventName ();}\
};
Thus, your GetEventFunction would look like this:
template<typename T, typename EventType>
EventType::function_type GetEventFunction(T* object)
{
return std::bind(event_traits<EventType>::Dispatch<T>, object);
}
If you do have the name of the member, then you don't need to know of a type -- assuming that member is not an overloaded member function.
template<typename T>
auto GetEventFunction(T& object)
-> decltype( std::bind(&T::onEvent, std::ref(object)) )
{ return std::bind(&T::onEvent, std::ref(object)); }
// Usage:
Foo f;
auto event = GetEventFunction(f);
Note that this is somewhat contrived, because the onEvent you mentioned doesn't take any arguments. If it did, you'd need more scaffolding. (I'd recommend writing a mem_fn that also accepts an object, unlike std::mem_fn.)

Using decltype in a late specified return in CRTP base class

I'm trying to use decltype in the late specified return of a member function in a CRTP base class and it's erroring with: invalid use of incomplete type const struct AnyOp<main()::<lambda(int)> >.
template<class Op>
struct Operation
{
template<class Foo>
auto operator()(const Foo &foo) const ->
typename std::enable_if<is_foo<Foo>::value,
decltype(static_cast<const Op*>(nullptr)->call_with_foo(foo))>::type
{
return static_cast<const Op*>(this)->call_with_foo(foo);
}
};
template<class Functor>
struct AnyOp : Operation<AnyOp<Functor> >
{
explicit AnyOp(Functor func) : func_(func) {}
template<class Foo>
bool call_with_foo(const Foo &foo) const
{
//do whatever
}
private:
Functor func_;
};
I'm basically trying to move all of the sfinae boiler plate into a base class so I don't need to repeat it for every Operation that I create (currently each operation has 6 different calls and there are ~50 operations so there is quite a lot of repetition with the enable_if's).
I've tried a solution which relied on overloading but one of the types which may be passed is anything that's callable(this can be a regular functor from C++03 or a C++0x lambda) which I bound to a std::function, unfortunately, the overhead from std::function, although very minimal, actually makes a difference in this application.
Is there a way to fix what I currently have or is there a better solution all together to solve this problem?
Thanks.
You are, as another answer describes already, trying to access a member of a class in one of the class' base class. That's going to fail because the member is yet undeclared at that point.
When it instantiates the base class, it instantiates all its member declarations, so it needs to know the return type. You can make the return type be dependent on Foo, which makes it delay the computation of the return type until Foo is known. This would change the base class like the following
// ignore<T, U> == identity<T>
template<typename T, typename Ignore>
struct ignore { typedef T type; };
template<class Op>
struct Operation
{
template<class Foo>
auto operator()(const Foo &foo) const ->
typename std::enable_if<is_foo<Foo>::value,
decltype(static_cast<typename ignore<const Op*, Foo>::type>(nullptr)->call_with_foo(foo))>::type
{
return static_cast<const Op*>(this)->call_with_foo(foo);
}
};
This artificially makes the static_cast cast to a type dependent on Foo, so it does not immediately require a complete Op type. Rather, the type needs to be complete when operator() is instantiated with the respective template argument.
You are trying to refer to a member of a class from one of its own base classes, which will fail since the class's body doesn't exist within its base class. Can you pass the logic for computing the return type of call_with_foo as a metafunction to the base class? Is that logic ever going to be complicated?
Another option, depending on how much flexibility you have in changing your class hierarchy (and remember that you have template typedefs), is to have the wrapper inherit from the implementation class rather than the other way around. For example, you can write a AddParensWrapper<T> that inherits from T and has operator() that forwards to T::call_with_foo. That will fix the dependency problem.

How to pass a method pointer as a template parameter

I am trying to write a code that calls a class method given as template parameter. To simplify, you can suppose the method has a single parameter (of an arbitrary type) and returns void. The goal is to avoid boilerplate in the calling site by not typing the parameter type. Here is a code sample:
template <class Method> class WrapMethod {
public:
template <class Object>
Param* getParam() { return &param_; }
Run(Object* obj) { (object->*method_)(param_); }
private:
typedef typename boost::mpl::at_c<boost::function_types::parameter_types<Method>, 1>::type Param;
Method method_;
Param param_
};
Now, in the calling site, I can use the method without ever writing the type of the parameter.
Foo foo;
WrapMethod<BOOST_TYPEOF(&Foo::Bar)> foo_bar;
foo_bar.GetParam()->FillWithSomething();
foo_bar.Run(foo);
So, this code works, and is almost what I want. The only problem is that I want to get rid of the BOOST_TYPEOF macro call in the calling site. I would like to be able to write something like WrapMethod<Foo::Bar> foo_bar instead of WrapMethod<BOOST_TYPEOF(&Foo::Bar)> foo_bar.
I suspect this is not possible, since there is no way of referring to a method signature other than using the method signature itself (which is a variable for WrapMethod, and something pretty large to type at the calling site) or getting the method pointer and then doing typeof.
Any hints on how to fix these or different approaches on how to avoid typing the parameter type in the calling site are appreciated.
Just to clarify my needs: the solution must not have the typename Param in the calling site. Also, it cannot call FillWithSomething from inside WrapMethod (or similar). Because that method name can change from Param type to Param type, it needs to live in the calling site. The solution I gave satisfies both these constraints, but needs the ugly BOOST_TYPEOF in the calling site (using it inside WrapMethod or other indirection would be fine since that is code my api users won't see as long as it is correct).
Response:
As far as I can say, there is no possible solution. This boil down to the fact that is impossible to write something like WrapMethod<&Foo::Bar>, if the signature of Bar is not known in advance, even though only the cardinality is necessary. More generally, you can't have template parameters that take values (not types) if the type is not fixed. For example, it is impossible to write something like typeof_literal<0>::type which evalutes to int and typeof_literal<&Foo::Bar>::type, which would evaluate to void (Foo*::)(Param) in my example. Notice that neither BOOST_TYPEOF or decltype would help because they need to live in the caling site and can't be buried deeper in the code. The legitimate but invalid syntax below would solve the problem:
template <template<class T> T value> struct typeof_literal {
typedef decltype(T) type;
};
In C++0x, as pointed in the selected response (and in others using BOOST_AUTO), one can use the auto keyword to achieve the same goal in a different way:
template <class T> WrapMethod<T> GetWrapMethod(T) { return WrapMethod<T>(); }
auto foo_bar = GetWrapMethod(&Foo::Bar);
Write it as:
template <typename Object, typename Param, void (Object::*F)(Param)>
class WrapMethod {
public:
Param* getParam() { return &param_; }
void Run(Object* obj) { (obj->*F)(param_); }
private:
Param param_;
};
and
Foo foo;
WrapMethod<Foo, Param, &Foo::Bar> foo_bar;
foo_bar.getParam()->FillWithSomething();
foo_bar.Run(foo);
EDIT: Showing a template function allowing to do the same thing without any special template wrappers:
template <typename Foo, typename Param>
void call(Foo& obj, void (Foo::*f)(Param))
{
Param param;
param.FillWithSomthing();
obj.*f(param);
}
and use it as:
Foo foo;
call(foo, &Foo::Bar);
2nd EDIT: Modifying the template function to take the initialization function as a parameter as well:
template <typename Foo, typename Param>
void call(Foo& obj, void (Foo::*f)(Param), void (Param::*init)())
{
Param param;
param.*init();
obj.*f(param);
}
and use it as:
Foo foo;
call(foo, &Foo::Bar, &Param::FillWithSomething);
If your compiler supports decltype, use decltype:
WrapMethod<decltype(&Foo::Bar)> foo_bar;
EDIT: or, if you really want to save typing and have a C++0x compliant compiler:
template <class T> WrapMethod<T> GetWrapMethod(T) { return WrapMethod<T>(); }
auto foo_bar= GetWrapMethod(&Foo::Bar);
EDIT2: Although, really, if you want it to look pretty you either have to expose users to the intricacies of the C++ language or wrap it yourself in a preprocessor macro:
#define WrapMethodBlah(func) WrapMethod<decltype(func)>
Have you considered using method templates?
template <typename T> void method(T & param)
{
//body
}
Now the compiler is able to implicitly determine parameter type
int i;
bool b;
method(i);
method(b);
Or you can provide type explicitly
method<int>(i);
You can provide specializations for different data types
template <> void method<int>(int param)
{
//body
}
When you are already allowing BOOST_TYEPOF(), consider using BOOST_AUTO() with an object generator function to allow type deduction:
template<class Method> WrapMethod<Method> makeWrapMethod(Method mfp) {
return WrapMethod<Method>(mfp);
}
BOOST_AUTO(foo_bar, makeWrapMethod(&Foo::Bar));
Okay let's have a go at this.
First of all, note that template parameter deduction is available (as noted in a couple of answers) with functions.
So, here is an implementation (sort of):
// WARNING: no virtual destructor, memory leaks, etc...
struct Foo
{
void func(int e) { std::cout << e << std::endl; }
};
template <class Object>
struct Wrapper
{
virtual void Run(Object& o) = 0;
};
template <class Object, class Param>
struct Wrap: Wrapper<Object>
{
typedef void (Object::*member_function)(Param);
Wrap(member_function func, Param param): mFunction(func), mParam(param) {}
member_function mFunction;
Param mParam;
virtual void Run(Object& o) { (o.*mFunction)(mParam); }
};
template <class Object, class Param>
Wrap<Object,Param>* makeWrapper(void (Object::*func)(Param), Param p = Param())
{
return new Wrap<Object,Param>(func, p);
}
int main(int argc, char* argv[])
{
Foo foo;
Wrap<Foo,int>* fooW = makeWrapper(&Foo::func);
fooW->mParam = 1;
fooW->Run(foo);
Wrapper<Foo>* fooW2 = makeWrapper(&Foo::func, 1);
fooW2->Run(foo);
return 0;
}
I think that using a base class is the native C++ way of hiding information by type erasure.

Semi-generic function

I have a bunch of overloaded functions that operate on certain data types such as int, double and strings. Most of these functions perform the same action, where only a specific set of data types are allowed. That means I cannot create a simple generic template function as I lose type safety (and potentially incurring a run-time problem for validation within the function).
Is it possible to create a "semi-generic compile time type safe function"? If so, how? If not, is this something that will come up in C++0x?
An (non-valid) idea;
template <typename T, restrict: int, std::string >
void foo(T bar);
...
foo((int)0); // OK
foo((std::string)"foobar"); // OK
foo((double)0.0); // Compile Error
Note: I realize I could create a class that has overloaded constructors and assignment operators and pass a variable of that class instead to the function.
Use sfinae
template<typename> struct restrict { };
template<> struct restrict<string> { typedef void type; };
template<> struct restrict<int> { typedef void type; };
template <typename T>
typename restrict<T>::type foo(T bar);
That foo will only be able to accept string or int for T. No hard compile time error occurs if you call foo(0.f), but rather if there is another function that accepts the argument, that one is taken instead.
You may create a "private" templatized function that is never exposed to the outside, and call it from your "safe" overloads.
By the way, usually there's the problem with exposing directly the templatized version: if the passed type isn't ok for it, a compilation error will be issued (unless you know your algorithm may expose subtle bugs with some data types).
You could probably work with templates specializations for the "restricted" types you want to allow. For all other types, you don't provide a template specialization so the generic "basic" template would be used. There you could use something like BOOST_STATIC_ASSERT to throw a compile error.
Here some pseudo-code to clarify my idea:
template <typename T>
void foo(T bar) {BOOST_STATIC_ASSERT(FALSE);}
template<> // specialized for double
void foo(double bar) {do_something_useful(bar);};
Perhaps a bit ugly solution, but functors could be an option:
class foo {
void operator()(double); // disable double type
public:
template<typename T>
void operator ()(T bar) {
// do something
}
};
void test() {
foo()(3); // compiles
foo()(2.3); // error
}
Edit: I inversed my solution
class foo {
template<typename T>
void operator ()(T bar, void* dummy) {
// do something
}
public:
// `int` is allowed
void operator ()(int i) {
operator ()(i, 0);
}
};
foo()(2.3); // unfortunately, compiles
foo()(3); // compiles
foo()("hi"); // error
To list an arbitrary selection of types I suppose you could use a typelist. E.g see the last part of my earlier answer.
The usage might be something like:
//TODO: enhance typelist declarations to hide the recursiveness
typedef t_list<std::string, t_list<int> > good_for_foo;
template <class T>
typename boost::enable_if<in_type_list<T, good_for_foo> >::type foo(T t);