在编写迭代器和const_iterator时避免代码重复

avoid code duplication when writing iterator and const_iterator

本文关键字:代码 iterator 迭代器 const      更新时间:2023-10-16

我正在尝试编写一个迭代器类,它可以覆盖const_iterator和迭代器类,以避免代码重复。

在阅读其他问题时,我看到了这篇文章,问的正是我想要的问题。最好的回应是这篇文章,它很好地用一段话解释了我需要做什么,但引用了我没有的书中的例子。我的尝试实现描述如下:

      template<bool c=0> //determines if it is a const_iterator or not
      class iterator{
         typedef std::random_access_iterator_tag iterator_category;
         typedef T value_type;
         typedef T value_type;
         typedef std::ptrdiff_t difference_type;
         typedef (c ? (const T*) : (T*)) pointer; //problem line
         typedef (c ? (const T&) : (T&)) reference; //problem line
      public:
         operator iterator<1>(){ return iterator<1>(*this) }
         ...
      }

我不知道如何使用三元操作符来确定类型定义。指定的行得到编译器错误"预期')'之前' ?的令牌"。我对文章的理解错了吗?

还要求编写一个转换构造函数,使所有const函数都可以转换非const形参。这是否意味着当使用const_iterators时,程序必须为每个参数构造新的迭代器?这似乎不是一个非常理想的解决方案。

三元操作符对类型不起作用。您可以使用std::conditional代替:

typedef typename std::conditional<c ,const T*, T*>::type pointer;