I want to create a class with a callback function, it should be possible to use either an external function as callback, or the class will assign a member function as callback by default. See my code sample here:
#include <functional>
class Foo
{
public:
typedef std::function<void(void)> CallbackType;
Foo(CallbackType callback = defaultCallback): _callback(callback) {}
// code sample works only if this function is defined static:
static void defaultCallback(void) {}
CallbackType _callback;
};
void externCallback(void) {}
int main()
{
Foo fooExtern(externCallback);
}
As mentioned in the code, the sample works only if 'defaultCallback' is defined static. When not using the static keyword, I get the error:
cannot convert ‘Foo::defaultCallback’ from type ‘void (Foo::)()’ to type ‘Foo::CallbackType {aka std::function}’
However, I want also to be able to use this class as a parent class, and I want to define the 'defaultCallback' as virtual (which is not possible at the same time when defining it as static). Has anyone a suggestion how I can make the code work without using a static member function as default constructor argument?