在编写迭代器和const_iterator时避免代码重复
avoid code duplication when writing iterator and const_iterator
我正在尝试编写一个迭代器类,它可以覆盖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;
相关文章:
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 代码在main()中运行,但在函数中出现错误
- 在VS代码中交叉编译Windows与Linux上的MinGW的SDL程序
- 编译包含字符串的代码时遇到问题
- 我在c++代码中生成了一个运行时#3异常
- 如何在linux终端中同时编译和运行c++代码
- 为cl.exe(Visual Studio代码)指定命令行C++版本
- 在Linux for Windows上编译C++代码时出错
- 我的字符计数代码计算错误.为什么
- 孤立代码块在结构中引发异常
- 在编译C++代码(具有dlib和opencv)到WASM时面临问题
- 为什么我的C#代码在调用回C++COM直到Task时会暂停.等待/线程.加入
- 处理小于cpu数据总线的数据类型.(c++转换为机器代码)
- 此代码是否违反一个定义规则
- 为什么我的代码在输出中增加了93天
- 我的简单if-else语句是如何无法访问的代码
- 使用动态分配的数组会导致代码分析发出虚假的C6386缓冲区溢出警告
- 为什么在这个代码结束循环中没有得到结束
- 在c代码之间共享数据的最佳方式
- 这个指针和内存代码打印是什么?我不知道是打印垃圾还是如何打印我需要的值