简体   繁体   English

boost :: bind绑定到类成员函数

[英]boost::bind to class member function

I'm trying to pass member function wrapped to stand-alone function via boost::bind . 我试图通过boost::bind包装成独立函数的成员函数传递给。 The following is the reduced sample. 以下是简化的示例。

// 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));

However I got compiler error with the text: 但是我得到了文本编译器错误:

/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&)

What the problem with the code and how to avoid such a problems? 代码有什么问题,如何避免此类问题?

Member function pointers do not include a context (as opposed to a lambda or boost::function ). 成员函数指针不包含上下文(与lambda或boost::function )。 To make the code work you need to replace your type definition of DoubleGetter to: 为了使代码正常工作,您需要将DoubleGetter的类型定义DoubleGetter为:

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

Also there is also no need to dereference the smart pointer when you supply the context ( Bar )(if you intend to do so anyway you can use the shorthand dereference operator directly): 同样,在提供上下文( Bar )时也无需取消引用智能指针(如果您打算这样做,则可以直接使用速记取消引用运算符):

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

I also noticed that you define a normal function pointer. 我还注意到,您定义了一个普通的函数指针。 In case you want to avoid use of boost::function completely you can use the following approach (I excluded non-altered parts): 如果您想完全避免使用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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM