c++ - 使用 boost MPL 或类似工具执行此迭代器过滤器的任何方式

标签 c++ boost c++11

本质上,我在一些情况下使用 boost::filter_iterator 为某些条件过滤迭代器。有一种情况,我想同时过滤 2 个条件,我们已经有一些预先存在的代码,但我想知道是否有一种惯用的方法可以使用 boost 或标准库来做到这一点:

    /*! TODO: Surely there should be something in std/boost to achieve this??? */
    /*! Filter for things that satisfy F1 and F2 */
    template <
        typename F1,
        typename F2,
        typename ArgT
    >
    struct filter_and
    {
        F1 f1;
        F2 f2;

        filter_and(F1 _f1, F2 _f2): f1(_f1), f2(_f2)
        {}

        inline bool operator() (ArgT const& arg) const
        {
            return f1(arg) && f2(arg);
        }
    };

如果一个解决方案需要 c++11,只要最新的 MSVC 可以处理它应该没问题。

最佳答案

试试这个:make_filter_iterator( it, [=](value_type const& v) { return f1(v) && f2(v); } );

对于更高级的...

bool and_in_order() { return true; }
template<typename F0, typename Funcs...>
bool and_in_order( F0&& f0, Funcs&&... funcs ) {
  return f0() && and_in_order(funcs...);
}

template<typename... Funcs>
struct and_unary_functors {
  std::tuple<Funcs...> funcs;
  template<typename Arg, typename seq=typename make_seq<sizeof...(Funcs)>::type>
  bool operator()(Arg&& arg) const;

  template<typename Arg, int...s>
  bool operator()<Arg, seq<s...>>(Arg&& arg) const {
    return and_in_order( [&](){ return get<s>(funcs)(arg); }... );
  }
};

template<typename... Funcs>
and_unary_functors<Funcs> make_and_unary( Funcs const&... funcs ) {
  return {std::make_tuple(funcs...)};
};

auto filter_it = make_filter_iterator( base_iterator, make_and_unary( f1, f2, f3, f4 ) );

或者类似的傻事。

关于c++ - 使用 boost MPL 或类似工具执行此迭代器过滤器的任何方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15098390/

相关文章:

c++ - 如何在 mfc 中更正此错误?

c++ - boost async_wait 并在绑定(bind)中添加 "this"

c++ - C++11 标准是否提供类似 boost::any 的东西?

c++ - 如何使用带有 future<T> vector 的基于范围的 for 循环

c++ - 两边都有省略号的 Lambda 包捕获 - 是什么意思?

c++ - 如何使用boost单例

c++ - 通过自定义语法使用 Boost Spirit 的流解析器

C++ 将派生类 shared_ptr 传递给模板函数

C++ 自定义时间日期结构到 utc 纪元

c++ - array::data 和 array::front 的用法