在成员函数内创建函子,而不将类作为参数

Creation of a functor inside a member function without taking the class as a argument

本文关键字:参数 函数 成员 创建      更新时间:2023-10-16

对神秘的解密表示歉意。

我希望创建以下类型的函子:

const boost::function<bool ()>& functor

请考虑类:

#include <boost/function.hpp>
class X { 
    public:
        bool foo();
        void bar() ;
};
void X::bar() {
    const boost::function<bool (X *)>& f = &X::foo;
}
bool X::foo() {
    std::cout << __func__ << " " << __LINE__ << " " << std::endl;
    return true;
}

我有:

const boost::function<bool (X *)>& f = &X::foo;

我可以有类似的东西吗

const boost::function<bool ()>& f = &X::foo;

使用boost::绑定还是其他东西?

谢谢

必须使用对象调用非静态成员函数。因此,必须始终隐式传递this指针作为其参数。

您可以使用boost::bind来实现此目的:

const boost::function<bool()>& f = boost::bind(&X::foo, this);