【问题标题】:Creation of a functor inside a member function without taking the class as a argument在成员函数内创建仿函数而不将类作为参数
【发布时间】:2015-06-15 15:26:39
【问题描述】:

为神秘的解密道歉。

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

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::bind 或其他方式?

谢谢

【问题讨论】:

  • 你为什么要对 boost 函数使用 const 引用?引用生命周期扩展通常会起作用,但是为临时对象而不是实际对象创建别名似乎毫无意义?
  • @Yakk 同意了。我的错。

标签: c++ boost bind functor


【解决方案1】:

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

您可以通过boost::bind 完成此操作:

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

【讨论】:

  • 附加信息:使用这种技术意味着对象 (*this) 将比函数对象 (f) 存在的时间更长。通过使用 boost::shared_ptr 作为参数而不是 this 来确保这一点是一个常见的习惯用法。
  • 嗨@Dale,谢谢。我试图通过以下方式做到这一点:stackoverflow.com/questions/30856388/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-29
相关资源
最近更新 更多