If I go like this:
typedef bool (*CallbackFunc)(int); //Typedefining a function pointer returning a bool and taking one int parameter (right?). void DoSomething(CallbackFunc callback);
That won't accept functors. So what is the best way to accept functors OR functions?
Looking at how the standard library does it, I see they use templates, which makes sense.
template <class funcType> void DoSomething(funcType callback);
That, because it is a templated parameter, accepts both functors and functions.
Nice... but is there a better way? What if I have a function that takes more than one callback:
//Two callbacks: template <class funcTypeA, class funcTypeB> void DoSomething(funcTypeA callbackA, funcTypeB callbackB); //Three callbacks: template <class funcTypeA, class funcTypeB, class funcTypeC> void DoSomething(funcTypeA callbackA, funcTypeB callbackB, funcTypeC callbackC);
I'm not really liking that too much. I just read up on std::function() (C++11) and am trying to understand it.
Can it really accept functions or functors (or lambdas)?
How does this work in practice?
typedef std::function<bool(int)> CallbackFunc; //template <class funcType>... Template not needed? void DoSomething(CallbackFunc callbackA, CallbackFunc callbackB, CallbackFunc callbackC);
Is that the proper usage? Am I understanding it correctly?
And I can pass one function to say, the first parameter, and two different classes as functors to the second and third parameter?
class FunctorA; FunctorA functorA; class DifferentFunctorB; DifferentFunctorB differentFunctorB; bool myFunction(int value); DoSomething(myFunction, functorA, differentFunctorB);
This is valid? Without DoSomething() itself being templated? With only one typedef of CallbackFunc taking just the return type and the parameters?