簡體   English   中英

boost :: bind綁定到類成員函數

[英]boost::bind to class member function

我試圖通過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&)

代碼有什么問題,如何避免此類問題?

成員函數指針不包含上下文(與lambda或boost::function )。 為了使代碼正常工作,您需要將DoubleGetter的類型定義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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM