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(???)
3
  • 2
    Look into std::function. Commented Sep 19, 2017 at 18:44
  • @user0042 Ok, so that seems to work.Any way to drop this to one line?: using std::placeholders::_1; callbacktype f_add_display2 = std::bind(&B::callbk, b, _1); s.startListen(f_add_display2); Commented Sep 19, 2017 at 18:58
  • 1
    See (3) in en.cppreference.com/w/cpp/thread/thread/thread Commented Sep 19, 2017 at 19:02

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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)...);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.