Steven Venham
Steven Venham

Reputation: 664

c++ class method callback Similar to std::thread

Using std::thread you are able to pass a classes method as the function to call.

Syntax:

std::thread myThread(&MyClass::handler, this);

1.What is the syntax of my function to imitate this behavior to allow for passing of class methods to my own callback routines?

2.How do I store this reference in a variable?

ex:

Myclass temp;
myfunction(&Myclass::somefunc,temp);

So?

typedef void(*mycallbacktype)(const std::string& someperamiter);
void myfunction(???)

Upvotes: 1

Views: 883

Answers (2)

army007
army007

Reputation: 561

To take a member function pointer to MyClass which returns void and takes no additional parameter declare it like -

void myfunction(void (MyClass::*somefunction)(), MyClass* obj)
{
  (obj->*somefunction)();
}

Here void (MyClass::*somefunction)() means somefunction is a pointer to member function of MyClass that takes no additional (except for implicit MyClass* as first parameter) parameter and returns void. See this for more about member function pointer.

To make the function more generic like std::thread declare it as following- The first one takes any non-member function (aka. free function) of any type

template<class F, class... Args>  
void myfunction(F&& f, Args&&... args)
{
    f(std::forward<Args>(args)...);
}

and second one takes the member function pointer of any type of any class.

template <class R, class C, class... Args> 
void myfunction(R(C::*mf)(Args...), C* pc, Args&&... args)
{
    (pc->*mf)(std::forward<Args>(args)...);
}

Upvotes: 0

Jodocus
Jodocus

Reputation: 7601

1.What is the syntax of my function to imitate this behavior to allow for passing of class methods to my own callback routines?

It is called "pointer-to-member". See What are the Pointer-to-Member ->* and .* Operators in C++? Your second question should be answered by that.

Upvotes: 1

Related Questions