否定增强范围过滤适配器

gnz*_*lbg 5 c++ lambda boost boost-range

是否可以/可实现否定升压滤波适配器,例如

std::vector<int> v = {1, 2, 3, 4, 5};
for(auto i : v | !filtered(is_even))
    std::cout << i << std::endl; // prints 1,3,5
Run Code Online (Sandbox Code Playgroud)

而不是在lambda表达式中做出否定?

动机:我使用过滤和lambda函数工作很多,但是当我不止一次使用过滤器时,我通常将它重构为自定义过滤器,例如

for(auto i : v | even) // note: my filters are more complex than even.
    std::cout << i << std::endl; // prints 2,4
Run Code Online (Sandbox Code Playgroud)

现在,当我需要否定时,我正在为它们构建一个自定义过滤器,例如

for(auto i : v | not_even)
    std::cout << i << std::endl; // prints 1,2,3
Run Code Online (Sandbox Code Playgroud)

但我会发现能够否定过滤器更好,例如

for(auto i : v | !even)
    std::cout << i << std::endl; // prints 1,2,3
Run Code Online (Sandbox Code Playgroud)

seh*_*ehe 7

以下是我在短时间内提出的建议:

#include <boost/range/adaptors.hpp>
#include <boost/functional.hpp>
#include <iostream>

namespace boost { 
    namespace range_detail { 

        template <typename T>
            auto operator!(filter_holder<T> const& f) -> decltype(adaptors::filtered(boost::not1(f.val)))
            {
                return adaptors::filtered(boost::not1(f.val));
            }
    }
}

int main()
{
    using namespace boost::adaptors;
    int const v[] = { 1, 2, 3, 4 };

    std::function<bool(int)> ll = [](int i){return 0 == (i%2);}; // WORKS
    // bool(*ll)(int) = [](int i){return 0 == (i%2);};           // WORKS
    // auto ll = [](int i){return 0 == (i%2);};                  // not yet

    auto even = filtered(ll);

    for (auto i : v | !even)
    {
        std::cout << i << '\n';
    }
}
Run Code Online (Sandbox Code Playgroud)

liveworkspace.org直播

请注意,目前处理表单的谓词function pointerstd::function<...>,而不是赤裸裸的lambda表达式,但(在GCC 4.7.2)