gpt4 book ai didi

c++ - 使用 boost::lambda::bind 有什么问题?

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:54:55 25 4
gpt4 key购买 nike

我正在尝试使用 boost::lambda::bind() 定义一个谓词,我将其传递给 Boost.Range 中的 find_if 算法。具体来说,我想搜索结构 vector 以找到特定成员具有指定值的第一个条目。我的例子如下:

#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"’

最佳答案

事实证明我没有包含所需的 header 。看来 <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;
}

关于c++ - 使用 boost::lambda::bind 有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16426828/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com