实现静态多态迭代器

时间:2016-04-17 18:49:09

标签: c++ c++11

我正在尝试为模板化类型层次结构实现迭代器接口,该层次结构使用静态多态性来避免与转发到实现的解决方案相关的开销(除非它可以被编译掉)。

我已经简要介绍了我正在构建的类型和接口,以及内联注释引用我遇到的问题。

下面直接显示的层次结构的顶部是通用Box<T>Convert方法可以通过将函数Box<U>应用于每个元素来返回新的U Func(Box<T>)

template<typename T>
class Box : public std::enable_shared_from_this<Box<T>> {
 public:
  template <typename Func>
  auto Convert(Func f) -> std::shared_ptr<Box<decltype(f(std::declval<T>()))>>;

  // This is what I am trying to achieve using a statically
  // compiled solution (e.g. without the use of a subclass
  // returning an implementation pointer and using pimpl).
  //
  // const_iterator cbegin();
  // const_iterator cend();

  // Uses the sub-class cbegin/cend interface
  std::vector<T> elements() {
    std::vector<T> result;
    std::copy(cbegin(), cend(), std::back_inserter(result);
    return result;
  }
};

这是一个ConvertedBox<T>,它存储指向Box和转换函数的指针。这里迭代器是引用变量rdd_的包装器,每次取消引用迭代器时都会应用func_

template<typename T, typename U, typename Func>
class ConvertedBox : public Box<T> {
 public:
  ConvertedBox(typename std::shared_ptr<Box<U>> box, Func func) :
    box_(box), func_(func)
  {}

  // Return iterator wrapper around box_->cbegin()
  //const_iterator cbegin()
  //const_iterator cend()

 private:
  std::shared_ptr<Box<U>> box_;
  Func func_;
};

最后,我们提供了一个包装具体向量的源框(其他来源在实践中使用)。

template<typename T>
class VectorBox : public Box<T> {
 public:
  ConvertedBox(const std::vector<T>& data) : data_(data)
  {}

  // Return iterator wrapper std::vector<T>::const_iterator
  //const_iterator cbegin() {
  //    return data_.cbegin();
  //}
  //const_iterator cend() { ... }

 private:
  const typename std::vector<T>& data_;
};

我尝试了各种涉及std::iterator的CRTP技巧,似乎无法将这些部分放在一起。我想避免任何依赖于boost的内容,但在C++11中假设任何内容都可以。

请注意,我在解决这个迭代器情况时遇到了问题(我所包含的其余部分仅用于上下文)。

0 个答案:

没有答案