如何使用boost :: bind绑定类成员函数?

时间:2011-02-08 04:27:21

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

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

2 个答案:

答案 0 :(得分:13)

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

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

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

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

答案 1 :(得分:2)

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

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