std::bind绑定类的成员函数

时间:2025-04-26 21:02:56

类的成员函数必须通过类的对象或者指针调用,因此在bind时,bind的第一个参数的位置来指定一个类的实列、指针或引用。

class Test
{
public:
    int funs(int val)
    {
        std::cout << "hello world " << val << std::endl;
        return val;
    }
};

class message
{
public:
    std::function<int()> fun;
};

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    Test test;
    message *mes = new message;
    mes->fun = std::bind(&Test::funs,test,2);
    cout << mes->fun() <<endl;

    return ();
}