【问题标题】:boost::bind to class member functionboost::绑定到类成员函数
【发布时间】:2013-10-08 09:21:52
【问题描述】:

我正在尝试通过boost::bind 将包装的成员函数传递给独立函数。以下是缩减样本。

// Foo.h
typedef const std::pair<double, double> (*DoubleGetter)(const std::string &);

class Foo : private boost::noncopyable {
public:
  explicit Foo(const std::string &s, DoubleGetter dg);
};

// Bar.h
struct Bar {
  const std::pair<double, double> getDoubles(const std::string &s);
};

// main.cpp
boost::shared_ptr<Bar> bar(new Bar());

std::string s = "test";
Foo foo(s, boost::bind(&Bar::getDoubles, *(bar.get()), _1));

但是我得到了文本的编译器错误:

/home/Loom/src/main.cpp:130: error: no matching function for call to 
‘Foo::Foo
( std::basic_string<char, std::char_traits<char>, std::allocator<char> >
, boost::_bi::bind_t
  < const std::pair<double, double>
  , boost::_mfi::mf1
    < const std::pair<double, double>
    , Bar
    , const std::string&
    >
  , boost::_bi::list2
    < boost::_bi::value<Bar>
    , boost::arg<1>
    >
  >
)’

/home/Loom/src/Foo.h:32: note: candidates are: 
Foo::Foo(const std::string&, const std::pair<double, double> (*)(const std::string&))

/home/Loom/src/Foo.h:26: note:
Foo::Foo(const Foo&)

代码有什么问题以及如何避免此类问题?

【问题讨论】:

    标签: c++ boost compiler-errors boost-bind member-functions


    【解决方案1】:

    成员函数指针不包含上下文(相对于 lambda 或 boost::function)。要使代码正常工作,您需要将 DoubleGetter 的类型定义替换为:

    typedef boost::function<const std::pair<double, double>(const std::string&)> DoubleGetter;
    

    此外,当您提供上下文 (Bar) 时,也无需取消引用智能指针(如果您打算这样做,您可以直接使用速记取消引用运算符):

    // Pass the pointer directly to increment the reference count (thanks Aleksander)
    Foo foo(s, boost::bind(&Bar::getDoubles, bar, _1));
    

    我还注意到您定义了一个普通的函数指针。如果您想完全避免使用 boost::function,您可以使用以下方法(我排除了未更改的部分):

    typedef const std::pair<double, double> (Bar::*DoubleGetter)(const std::string &);
    
    class Foo : private boost::noncopyable {
    public:
      explicit Foo(const std::string &s, Bar& bar, DoubleGetter dg);
      // Call dg by using: (bar.*dg)(s);
    };
    
    // Instantiate Foo with:
    Foo foo(s, *bar, &Bar::getDoubles);
    

    【讨论】:

    • 你为什么要取消对 sp 的引用?只需简单地将 bar 作为共享指针传递给 boost 绑定,这将增加 sp“所有者” - 这将确保 bar 不会被删除。在这种情况下,这不是问题 - 但在其他情况下可能是。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-06-23
    • 2013-07-13
    • 1970-01-01
    • 1970-01-01
    • 2014-03-02
    • 2019-09-14
    • 1970-01-01
    相关资源
    最近更新 更多