c ++存储指向未知类的成员函数的指针

And*_*rew 5 c++ pointers member-function-pointers function-pointers callback

我想存储一个指向对象的指针和一个指向它的已知签名方法的指针.如果我知道该类,那么这个指针有类型:

int (MyClass::*pt2Member)(float, char, char)
Run Code Online (Sandbox Code Playgroud)

但是,如果我不知道类型,我怎么能存储指针?

我想做这样的事情:

myObject.callThisFuncLater(&otherObject, &otherObject::method)
Run Code Online (Sandbox Code Playgroud)

我怎么能存放指向方法methodmyObject后来又打电话了吗?

Bri*_*man 5

如果您可以访问TR1 STL库扩展(在gcc和Visual Studio 2008及更高版本上可用),最简单的方法是使用.std :: function和std :: bind可用于包装稍后可以调用的调用.此功能也可用于boost函数和boost绑定:

#include <functional>

class MyClass {
public:
  template<typename T> callThisFuncLater(T& otherObject,
                                         int(T::*)(float, char, char) method) {
    return storedInvocation_ = std::bind(otherObject, 
                                  method, 
                                  std::placeholders::_1,   // float
                                  std::placeholders::_2,   // char
                                  std::placeholders::_3);  // char
  }

  int callStoredInvocation(float a, char b, char c) {
    storedInvocation_(a, b, c);
  }

private:
  std::function<int(float, char, char)> storedInvocation_;
};
Run Code Online (Sandbox Code Playgroud)


Dan*_*lli 2

您可以使用boost::function( 和boost::bind) 来存储稍后调用的一段代码。

class MyClass
{
public:
    void callThisFuncLater( boost::function< int (float, char, char) > callBack );
};
...
myObject.callThisFuncLater( boost::bind( &otherObject::method, &otherObject ) );
Run Code Online (Sandbox Code Playgroud)