4

我正在尝试编写一个可以涵盖 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) }
         ...
      }

我不知道如何使用三元运算符来确定 typedef。指定的行在 '?' 之前得到编译器错误“预期的 ')' 令牌”。我对文章的理解有误吗?

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

4

1 回答 1

4

三元运算符不适用于类型。您可以std::conditional改用:

typedef typename std::conditional<c ,const T*, T*>::type pointer; 
于 2013-03-03T06:18:07.790 回答