c ++:boost :: bind可用于将成员函数转换为预期的函数指针签名吗?

时间:2011-07-15 14:50:31

标签: c++ boost-bind member-function-pointers

我正在使用第三方库,它将函数指针传递给方法调用。

class RTSPClient{
public:
...
  typedef void (responseHandler)(RTSPClient* rtspClient,
             int resultCode, char* resultString);
...
  unsigned sendOptionsCommand(responseHandler* responseHandler, 
             Authenticator* authenticator = NULL);
};

正常使用情况如下:

void continueAfterOPTIONS(RTSPClient* client, 
             int resultCode, char* resultString);
....
RTSPClient* pClient;
....
pClient->sendOptionsCommand(continueAfterOPTIONS, NULL);

现在我想将continueAfterOPTIONS方法作为类的成员函数。 通常我使用boost :: bind来做到这一点:

pRtspClient>sendOptionsCommand(boost::bind(&RtspClientSessionManager::continueAfterOPTIONS, this), NULL);

导致

error C2664: 'RTSPClient::sendOptionsCommand' : cannot convert parameter 1 from 'boost::_bi::bind_t<R,F,L>' to 'RTSPClient::responseHandler (__cdecl *)'

我尝试为函数的参数添加位置持有者,这没有任何区别。我正在尝试做什么?有没有办法来转换绑定结果?

谢谢!

3 个答案:

答案 0 :(得分:3)

没有开箱即用。但是,让我勾勒出你如何做到这一点。

struct Foo : RTSPClient {
  boost::function<void(int resultCode, char* resultString)> bound;
  Foo(boost::function<void(int resultCode, char* resultString)> bound) : bound(bound) {}

  // Need a static method to get a regaulr function pointer
  static void CallBack(RTSPClient* _this, int resultCode, char* resultString) {
     _this->CallBack(int resultCode, char* resultString
  void CallBack(int resultCode, char* resultString) {
    bound();
  }
};

如果您可以从RtspClientSessionManager

派生RtspClient,那当然会更容易

答案 1 :(得分:2)

boost::bind生成一个函数对象,它与指向函数的指针完全不同。它是一个重载operator()的对象。

我说它不能在这里使用。

答案 2 :(得分:1)

你不能这样做。 bind库创建函数对象,而不是实函数,生成的指针的类型也不同。

相关问题