2013-05-07 64 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; 
} 
相关问题