c++ - boost 具有不同谓词的过滤器迭代器

标签 c++ templates boost iterator polymorphism

我正在尝试实现一个返回 boost::filter_iterator 对(开始、结束)的方法。

我希望这个方法在过滤方面是可定制的,但我不知道如何解决这个问题,因为当我输入过滤器迭代器范围时,我必须对我想要使用的谓词进行硬编码,并且我无法选择它取决于该方法在输入中接收的参数。

我想要这样的东西:

enum FilterType
{
    FilterOnState = 0,
    FilterOnValue,
    FilterOnSize,
    FilterOnWhatever...
}

typedef boost::filter_iterator<PredicateStruct, std::list<Object>::iterator> filter_iterator;

std::pair<filter_iterator, filter_iterator> filterObjects(FilterType filterType);

我也考虑了一种可能的模板解决方案,但我需要客户端在调用过滤器之前访问谓词实现并实例化适合他需要的实例,他几乎自己完成所有工作:这就是为什么我会最喜欢基于枚举的解决方案。

template<typename P>
std::pair<boost::filter_iterator<P, std::list<Object>::iterator>, 
          boost::filter_iterator<P, std::list<Object>::iterator>> filterObjects(P& predicate);

谓词“基类”是否是基于枚举的实现的可能解决方案?

提前非常感谢! 贾科莫

最佳答案

为什么不简单地提供预定义谓词而不是枚举值?

struct predef_predicate{  
  predef_predicate(FilterType f)
    : filt(f) {}

  template<class T>
  bool operator()(T const& v) const{
    // filter in whatever way...
  }

private:
  FilterType filt;
};

namespace { // guard against ODR violations
predef_predicate const filter_state(FilterOnState);
predef_predicate const filter_values(FilterOnValue);
// ...
}

然后,不用重新发明轮子,只需使用 Boost.Range's filtered adaptor .

#include <vector>
#include <iterator>
#include <boost/range/adaptor/filtered.hpp>
#include <boost/range/algorith/copy.hpp>

int main(){
  std::vector<int> v;
  // fill v
  std::vector<int> filtered;
  boost::copy(v | boost::adaptors::filtered(filter_values),
      std::back_inserter(filtered));
}

在 C++11 中,由于 lambda,创建谓词的行为变得更加容易。

关于c++ - boost 具有不同谓词的过滤器迭代器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9430476/

相关文章:

c# - 跨平台最佳 MVC 模型到 Controller 的消息传递方法(C#、Objective-C++)

c++ - 为什么模板只能在头文件中实现?

c++ - 使用 boost.pool 而不是 'new' 作为对象容器

跨平台项目中的 C# 与 C++

c++ - 使用 lambda 捕获类后没有合适的复制构造函数

c++ - 通用 Lambda 之间的差异

c++ - 带有模板包 : disabling member if no template arguments 的 SFINAE

c++ - 不能为对象的 shared_ptr 的 vector 调用没有对象的成员函数

c++ - 如何摆脱 FormatMessageA 错误消息中附加的 ".\r\n"字符?

c++ - 如何为其他类成员函数编写模板包装器方法?