接收函子作为参数的最通用方法

Most general way to receive a functor as a parameter?

本文关键字:方法 参数      更新时间:2023-10-16

我正在为多线程方案编写一个包装器。它的操作应该类似于定时器。

我有一个特殊的类(clock),它实现了一个叫做tick的函数,这个函数应该传递给构造函数。如何将c++风格的函数(myClass::myfunction,与C的约定相反)描述为方法或构造函数的参数?

谁能告诉我这种构造函数的声明?
clock myInstance(otherClass::aMethod)
myInstance.tick(); // Should call otherClass::aMethod
myInstance.tick();

c++ 11和Bind有帮助吗?

可以调用类的静态成员函数,也可以调用对象的非静态成员函数。非静态成员函数需要有对象的上下文(this指针)。

下面是一个简化的示例,说明如何使用函子和bind来调用成员函数。

#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
}

您不需要为此使用std::function。您需要有两个指针:一个是类对象,另一个指向该类的方法。简单地说,您需要使它能够做到:

CallNonVirtual(pClassPtr, pFuncAddr);
因此,你需要这两个参数,这样你就可以把叫做
(pClassPtr->*pFuncAddr)(); // Assuming no parameter

您可以这样做:

class Clock
{
    COtherClass* pClassPtr; 
    /// Typedef simplifies
    typedef void (COtherClass::*TargetFuncType)();
    TargetFuncType pFuncAddr;
public:
    Clock(COtherClass* pOther, TargetFuncType pFunc) : 
          pClassPtr(pOther), pFuncAddr(pFunc) 
   { 
   }
   void tick()
   {
       (pClassPtr->*pFuncAddr)();
   }
 };      

拨打电话:

int main()
{
   COtherClass Obj;
   Clock theClock(&Obj, &COtherClass::TheNonStatic);
   theClock.tick();
}