【问题标题】:c++: Can boost::bind be used to convert member function to expected function pointer signature?c ++:可以使用 boost::bind 将成员函数转换为预期的函数指针签名吗?
【发布时间】:2011-07-15 14:50:30
【问题描述】:

我正在使用将函数指针传递给方法调用的第 3 方库。

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 *)'

我尝试为函数的参数添加占位符,但这没有任何区别。我正在尝试做的事情可能吗?有没有办法转换绑定结果?

谢谢!

【问题讨论】:

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


    【解决方案1】:

    不是开箱即用的。不过,让我来勾勒一下如何做到这一点。

    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();
      }
    };
    

    如果你可以从RtspClient 导出你的RtspClientSessionManager 当然更容易

    【讨论】:

    • 谢谢,这正是我所需要的 :)
    【解决方案2】:

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

    我会说它不能在这里使用。

    【讨论】:

      【解决方案3】:

      你不能那样做。 bind库创建的是函数对象,不是真正的函数,生成的指针类型会有所不同。

      【讨论】:

        猜你喜欢
        • 2018-08-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-10-25
        • 2011-09-22
        • 2013-09-21
        • 2015-12-11
        相关资源
        最近更新 更多