【问题标题】:avoid code duplication when writing iterator and const_iterator编写迭代器和 const_iterator 时避免代码重复
【发布时间】:2013-03-03 06:05:43
【问题描述】:

我正在尝试编写一个可以同时涵盖 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 ‘)’ before ‘?’ token”。我对文章的理解有误吗?

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

【问题讨论】:

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


【解决方案1】:

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

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

【讨论】:

  • 啊!!当他说“编译时?:操作员”时,它太具有误导性了!我现在觉得很傻。非常感谢!
  • 虽然这可行,但我总是对为避免一些代码重复而编写的额外代码量着迷。 :-) 当您最终拥有更多代码时,您并没有降低复杂性——这是最初的目标。请参阅 this "solution" 以获取有关如何使用两个复杂类型转换来保存一个 return n; 的示例。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-28
  • 2021-01-15
  • 2011-01-10
  • 2011-11-18
相关资源
最近更新 更多