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

标签 c++ lambda bind negate

假设我有这种类型:

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/

相关文章:

c# - 如何在 C# 中创建未转义的十六进制字节字符串

node.js - 为 NodeJS Lambda 函数重用 Redis 连接

java - 使用Java和AWS Lambda函数解析JSON错误

jquery - 将拖动事件绑定(bind)到 div 中的图像 - jquery

javascript - 在 React 中绑定(bind)函数时如何传递事件参数?

jquery - 复选框绑定(bind) CHANGE 事件

c++ - 我在 visual studio 6.0 中使用 boost 1.3.0

c++ - 为什么我的函数代码中存在一个模棱两可的地方,即以十进制n的二进制表示形式计算1的数量

c++ - 在 Mac OS X 上使用 Qwt

java - 有没有一种优雅的方法来获取Java中多个方法返回的第一个非空值?