c ++类方法回调类似于std :: thread

时间:2017-09-19 18:43:56

标签: c++ callback

使用std :: thread,您可以将classes方法作为要调用的函数传递。

语法:

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

1.我的函数的语法是什么模仿这种行为以允许将类方法传递给我自己的回调例程?

2.如何将此引用存储在变量中?

例如:

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

因此?

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

2 个答案:

答案 0 :(得分:1)

  

1.我的函数的语法是什么模仿这种行为以允许将类方法传递给我自己的回调例程?

它被称为“指向成员的指针”。见What are the Pointer-to-Member ->* and .* Operators in C++? 你应该回答第二个问题。

答案 1 :(得分:0)

获取一个成员函数指针MyClass返回void并且没有其他参数声明它像 -

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

这里void (MyClass::*somefunction)()表示somefunction是指向MyClass的成员函数的指针,它不需要额外的(除了隐式MyClass*作为第一个参数)参数并返回{{1 }}。有关成员函数指针的更多信息,请参阅this

为使函数更通用,如void,请将其声明如下 - 第一个采用任何类型的任何非成员函数(也称为自由函数)

std::thread

,第二个获取任何类的任何类型的成员函数指针。

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