boost :: bind到类成员函数

时间:2013-10-08 09:21:52

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

我正在尝试通过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&)

代码有什么问题以及如何避免这样的问题?

1 个答案:

答案 0 :(得分:2)

成员函数指针不包含上下文(而不是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);
相关问题