我试图使用boost::lambda::bind()
来定义我在Boost.Range中传递给find_if
算法的谓词。具体来说,我想搜索一个结构向量,找到第一个特定成员具有指定值的项。我的例子如下:
#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下)时,我得到了典型的模板实例化错误,表明没有发现与bind()
和const char []
返回的类型兼容的operator==
。我也尝试过其他类型,如int
,有相同的结果。
我一定错过了bind()
使用的一些小细节,但我看不到它;似乎这类事情应该基于文档工作。我错了吗?
Edit:这是编译器输出的第一部分:
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"’
原来我没有包括必需的标题。似乎<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;
}