2013-05-07 67 views
4

我試圖用boost::lambda::bind()來定義一個謂詞,我將它傳遞給Boost.Range中的find_if算法。具體來說,我想搜索一個結構向量來查找特定成員具有指定值的第一個條目。我的例子如下:這種使用boost :: lambda :: bind有什麼不對?

#include <boost/lambda/bind.hpp> 
#include <boost/range/algorithm/find_if.hpp> 
#include <vector> 

using namespace std; 
using namespace boost; 
using namespace boost::lambda; 

struct foo 
{ 
    string s; 
    int x; 
}; 

int main() 
{ 
    // create list and add a couple entries 
    vector<foo> fooList; 
    foo f1 = {"abc", 1}; 
    foo f2 = {"def", 2}; 
    fooList.push_back(f1); 
    fooList.push_back(f2); 
    // search for a value with the desired member 
    //  fails with a compile error! 
    range_iterator<vector<foo> > it = find_if(fooList, boost::lambda::bind(&foo::s, _1) == string("abc")); 
    return 0; 
} 

當我嘗試編譯這個(gcc 4.7.2下),我得到的模板實例錯誤的典型滲出,這表明沒有operator==發現與類型兼容由bind()const char []返回。我也嘗試過其他類型,如int,結果相同。

我必須缺少bind()用法的一些小細節,但我看不到它;似乎這種事情應該基於文檔工作。我錯了嗎?

編輯:以下是編譯器輸出的第一部分:

test.cc:24:92: error: no match for ‘operator==’ in ‘boost::lambda::bind(const Arg1&, const Arg2&) [with Arg1 = std::basic_string<char> foo::*; Arg2 = boost::lambda::lambda_functor<boost::lambda::placeholder<1> >; typename boost::lambda::detail::bind_tuple_mapper<const Arg1, const Arg2>::type = boost::tuples::tuple<std::basic_string<char> foo::* const, const boost::lambda::lambda_functor<boost::lambda::placeholder<1> >, boost::tuples::null_type, boost::tuples::null_type, boost::tuples::null_type, boost::tuples::null_type, boost::tuples::null_type, boost::tuples::null_type, boost::tuples::null_type, boost::tuples::null_type>]((* & boost::lambda::{anonymous}::_1)) == "abc"’ 
+0

感謝您的建議。它調用'boost :: lambda :: bind'。我將用實際的編譯器錯誤編輯上述內容。 – 2013-05-07 19:21:40

回答

4

原來,我是不包括所需的頭部。看起來<boost/lambda/bind.hpp>只能帶來bind功能,並且不包括運算符爲結果類型的重載。如果我在上面添加#include <boost/lambda/lambda.hpp>,那麼它解決了我引用的編譯器錯誤。最終的修改後的代碼(定影在從find_if()的返回值的類型另一個錯誤)如下:

#include <boost/lambda/bind.hpp> 
#include <boost/lambda/lambda.hpp> 
#include <boost/range/algorithm/find_if.hpp> 
#include <string> 
#include <vector> 

using namespace std; 
using namespace boost; 
using namespace boost::lambda; 

struct foo 
{ 
    string s; 
    int x; 
}; 

int main() 
{ 
    // create list and add a couple entries 
    vector<foo> fooList; 
    foo f1 = {"abc", 1}; 
    foo f2 = {"def", 2}; 
    fooList.push_back(f1); 
    fooList.push_back(f2); 
    // search for a value with the desired member 
    typename range_iterator<vector<foo> >::type it = find_if(fooList, bind(&foo::s, _1) == "abc"); 
    return 0; 
} 
相關問題