2012-10-02 53 views
3

我想使用boost :: bind將curried函數鏈接在一起,並且得到我無法解析的編譯器錯誤。我可以做這最簡單的例子編譯失敗:boost :: bind成員函數 - 部分應用程序鏈接

#include <iostream> 
#include <boost/bind.hpp> 

class A 
{ 
public: 
    template <typename F> 
    void g(F fn, char c) 
    { 
     fn(c); 
    } 

    void h(char c) 
    { 
     std::cout << c << std::endl; 
    } 

    template <typename F> 
    void f(F fn, char c) 
    { 
     boost::bind(&A::g<F>, this, fn, ::_1)(c); 
    } 
}; 

int main(int argc, char** argv) 
{ 
    char c = 'a'; 
    A a; 
    a.f(boost::bind(&A::h, &a, ::_1), c); 
} 

失敗,此錯誤:

In file included from /usr/include/boost/bind.hpp:22, 
       from test8.cpp:2: 
/usr/include/boost/bind/bind.hpp: In member function ‘void boost::_bi::list3<A1, A2, A3>::operator()(boost::_bi::type<void>, F&, A&, int) [with F = boost::_mfi::mf2<void, A, boost::_bi::bind_t<void, boost::_mfi::mf1<void, A, char>, boost::_bi::list2<boost::_bi::value<A*>, boost::arg<1> > >, char>, A = boost::_bi::list1<char&>, A1 = boost::_bi::value<A*>, A2 = boost::_bi::bind_t<void, boost::_mfi::mf1<void, A, char>, boost::_bi::list2<boost::_bi::value<A*>, boost::arg<1> > >, A3 = boost::arg<1>]’: 
/usr/include/boost/bind/bind_template.hpp:32: instantiated from ‘typename boost::_bi::result_traits<R, F>::type boost::_bi::bind_t<R, F, L>::operator()(A1&) [with A1 = char, R = void, F = boost::_mfi::mf2<void, A, boost::_bi::bind_t<void, boost::_mfi::mf1<void, A, char>, boost::_bi::list2<boost::_bi::value<A*>, boost::arg<1> > >, char>, L = boost::_bi::list3<boost::_bi::value<A*>, boost::_bi::bind_t<void, boost::_mfi::mf1<void, A, char>, boost::_bi::list2<boost::_bi::value<A*>, boost::arg<1> > >, boost::arg<1> >]’ 
test8.cpp:21: instantiated from ‘void A::f(F, char) [with F = boost::_bi::bind_t<void, boost::_mfi::mf1<void, A, char>, boost::_bi::list2<boost::_bi::value<A*>, boost::arg<1> > >]’ 
test8.cpp:29: instantiated from here 
/usr/include/boost/bind/bind.hpp:385: error: invalid use of void expression 

這是使用

$ g++ --version 
g++ (Ubuntu 4.4.3-4ubuntu5.1) 4.4.3 
+4

注意的是,當你經過升壓的結果::綁定到另一個的boost ::綁定,它會調用它,而不是沿着它傳遞作爲參數。爲了防止它被調用,將其包裝在boost :: protect() – PlasmaHH

回答

6

您需要在這樣的情況下使用boost::protect(),當您將綁定表達式傳遞給另一個綁定調用,但不希望在評估外部綁定函數的參數期間調用嵌套表達式,而是希望嵌套容器d表達式作爲外部函數的參數傳遞。 這將是:

boost::bind(&A::g<F>, this, boost::protect(fn), ::_1)(c); 
+0

中修復它,謝謝!我並不知道boost :: protect。文檔在這裏供將來參考:http://www.boost.org/doc/libs/1_51_0/libs/bind/bind.html#nested_binds –

相關問題