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

时间:2013-03-03 06:05:44

标签: c++ templates stl iterator code-duplication

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

在阅读其他一些问题时,我遇到this post,问我想要的确切问题。最好的回答是this article做了一个体面的工作,解释了我在一个段落中需要做什么,但是参考了我没有的书中的例子。我尝试实现所描述的内容如下:

      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) }
         ...
      }

我无法弄清楚如何使用三元运算符来确定typedef。指定的行在'?'标记“之前得到编译器错误” expected')'。我是否错误地解释了这篇文章?

此外,它说写一个转换构造函数,以便我的所有const函数都可以转换非const参数。这是不是意味着程序在使用const_iterators时必须为每个参数繁琐地构造新的迭代器?它似乎不是一个非常理想的解决方案。

1 个答案:

答案 0 :(得分:4)

三元运算符在类型上不像那样工作。您可以改为使用std::conditional

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