2013-10-08 72 views
0

我試圖通過boost::bind將成員函數封裝到獨立函數。以下是縮小的樣本。boost ::綁定到類成員函數

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

什麼用代碼和問題如何避免這樣的問題呢?

回答

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

我還注意到你定義了一個正常的函數指針。如果你想避免使用升壓功能的完全::您可以用下面的辦法(我排除未改變的部分):

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); 
+2

你爲什麼derefencing藻?只需簡單地將bar作爲共享指針傳遞給boost綁定即可增加sp「所有者」 - 這將確保bar不會被刪除。在這種情況下,這不是問題 - 但在其他情況下也可能是這樣。 –