gpt4 book ai didi

c++ - 如何否定 boost::lambda:bind?

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:58:18 29 4
gpt4 key购买 nike

假设我有这种类型:

typedef boost::function<bool (Foo)> filter_function;

以及那些“过滤函数”的 vector :

std::vector<filter_function> filters;

如果要调用所有的过滤函数,一个一个调用,只有最后一个调用返回true。

灵感来自 a previous question ,我最后写道:

bool Bar::filterFoo(Foo& foo)
{
return (std::find_if(filters.begin(), filters.end(), boost::lambda::bind(boost::lambda::_1, foo)) == filters.end());
}

但这是错误的:lambda 的返回值应该取反。

我尝试在不同的地方使用 std::not1std::not2 但找不到任何不以(漂亮详细)编译错误。

执行此操作的正确方法是什么?

最佳答案

您可以简单地否定返回值。

bool Bar::filterFoo(Foo& foo)
{
return (std::find_if(filters.begin(), filters.end(), !boost::lambda::bind(boost::lambda::_1, foo)) == filters.end());
}

或者你可以使用来自 c++0X 的 lambda

bool Bar::filterFoo(Foo& foo)
{
return (std::find_if(filters.begin(), filters.end(), [&foo](filter_function& f){
return !f(foo);
}
) == filters.end());
}

展示至少适用于 VS2010 的完整示例。

#include <iostream>
#include <vector>
#include <boost/function.hpp>
#include <boost/lambda/lambda.hpp>
#include <boost/bind.hpp>
#include <boost/lambda/bind.hpp>

using namespace std;

struct Foo{};

typedef boost::function<bool (Foo)> filter_function;
std::vector<filter_function> filters;

static int g_c = 0;
bool MyFunc(Foo /*foo*/)
{
if(g_c > 1)
return true;
g_c++;
return false;
}
bool filterFoo(Foo& foo)
{
return (std::find_if(filters.begin(), filters.end(), boost::lambda::bind(boost::lambda::_1, foo)) == filters.end());
}
bool negatefilterFoo(Foo& foo)
{
return (std::find_if(filters.begin(), filters.end(), !boost::lambda::bind(boost::lambda::_1, foo)) == filters.end());
}

int main()
{
Foo f;
filters.push_back(boost::bind(&MyFunc, _1));
filters.push_back(boost::bind(&MyFunc, _1));
filters.push_back(boost::bind(&MyFunc, _1));
std::cout << filterFoo(f) << std::endl;
std::cout << negatefilterFoo(f) << std::endl;
return 0;
}

它在我的机器上返回 0 和 1。

关于c++ - 如何否定 boost::lambda:bind?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6507865/

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