1

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(???)
Steven Venham
  • 600
  • 1
  • 3
  • 18

2 Answers2

1

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.

Jodocus
  • 7,493
  • 1
  • 29
  • 45
0

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)...);
}
army007
  • 551
  • 4
  • 20