How can I use boost::bind to bind a class member function?

独自空忆成欢 提交于 2020-01-02 03:46:04

问题


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

回答1:


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

You need to use placeholders for the two arguments:

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

The placeholders allow you to say "I'm only binding certain arguments; other arguments will be provided later."




回答2:


And if you want create portable code - specify namespace of placeholders directly:

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


来源:https://stackoverflow.com/questions/4929537/how-can-i-use-boostbind-to-bind-a-class-member-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!