【问题标题】:How can I use boost::bind to bind a class member function?如何使用 boost::bind 绑定类成员函数?
【发布时间】:2011-06-23 04:57:27
【问题描述】:
#include <QtCore/QCoreApplication>
#include <boost/bind.hpp>
#include <boost/function.hpp>

class button
{
 public:

    boost::function<void()> onClick;
    boost::function<void(int ,double )> onClick2;
};

class player
{
 public:
    void play(int i,double o){}
    void stop(){}
};

button playButton, stopButton;
player thePlayer;

void connect()
{
    //error C2298: 'return' : illegal operation on pointer to member function expression 
    playButton.onClick2 = boost::bind(&player::play, &thePlayer);
    stopButton.onClick = boost::bind(&player::stop, &thePlayer);
}

int main(int argc, char *argv[])

{

    QCoreApplication a(argc, argv);
    connect();
    return a.exec();
}

【问题讨论】:

    标签: c++ boost c++11 boost-bind boost-function


    【解决方案1】:
    boost::bind(&player::play, &thePlayer)
    

    您需要为两个参数使用占位符:

    boost::bind(&player::play, &thePlayer, _1, _2)
    

    占位符允许您说“我只绑定某些参数;其他参数将在稍后提供。”

    【讨论】:

      【解决方案2】:

      如果您想创建可移植代码 - 直接指定占位符的命名空间:

      boost::bind( &player::play, &thePlayer, ::_1, ::_2 ); // Placeholders of boost::bind are placed in global namespace.
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-09-14
        • 2016-02-13
        • 1970-01-01
        • 2013-11-12
        • 1970-01-01
        • 2011-01-01
        • 2011-01-19
        • 1970-01-01
        相关资源
        最近更新 更多