我正在为多线程方案编写一个包装器.它应该像计时器一样操作.
我有一个特定的class(clock),它实现了一个tick应该传递给构造函数的函数.如何将C++样式函数(myClass :: myfunction,而不是C约定)描述为方法或构造函数的参数?
有人能够向我展示这种构造函数的声明吗?
clock myInstance(otherClass::aMethod)
myInstance.tick(); // Should call otherClass::aMethod
myInstance.tick();
Run Code Online (Sandbox Code Playgroud)
C++ 11和Bind有帮助吗?
您可以调用类的静态成员函数或对象的非静态成员函数.非静态成员函数需要具有对象(this指针)的上下文.
这是一个简单的例子,说明如何使用仿函数和绑定来调用成员函数.
#include <functional>
class clock
{
public:
clock(const std::function<void()>& tocall) : m_tocall(tocall) {}
void tick() {m_tocall();}
private:
std::function<void()> m_tocall;
};
class otherclass
{
public:
void aMethod() {}
};
int main(int argc, char *argv[])
{
otherclass A;
clock c( std::bind(&otherclass::aMethod, &A) );
c.tick(); // Will end up calling aMethod() of object A
}
Run Code Online (Sandbox Code Playgroud)