3

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?

donald
  • 170
  • 4
  • 1
    There is an important difference between a static method and a common class method here you have a possible solution: http://stackoverflow.com/questions/7582546/using-generic-stdfunction-objects-with-member-functions-in-one-class – Marco Apr 07 '16 at 09:24
  • @Marco Thanks, that was really useful, I think I can do it that way. – donald Apr 07 '16 at 11:54

1 Answers1

3
class Foo
{
public:
  using CallbackType = std::function<void(void)>;

  Foo() : Foo([this]{defaultCallback();}) {}

  explicit Foo(CallbackType callback) : _callback(callback) {}  

  void defaultCallback(void) {}

  CallbackType _callback;
};
Piotr Skotnicki
  • 46,953
  • 7
  • 118
  • 160