【发布时间】: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 时必须繁琐地为每个参数构造新的迭代器?这似乎不是一个非常理想的解决方案。
【问题讨论】:
-
How to avoid code duplication implementing const and non-const iterators? 的可能重复项或将问题最小化到
?问题;-)
标签: c++ templates stl iterator code-duplication