c++ - c++ 分配器特征引用和 const_reference 缺失以及迭代器到 const 迭代器的转换
问题描述
我正在尝试使用迭代器实现自定义标准兼容容器类。
为此,我开始定义容器类和迭代器的特征要使用的公共类型定义。
我想让它符合 c++17 并尽量不使用 c++20 删除的功能或不推荐使用 c++17。
这就是我得到的:
template <typename T, typename Alloc = std::allocator<T>>
class container {
using allocator_type = Alloc;
using value_type = std::allocator_traits<Alloc>::value_type;
using pointer = std::allocator_traits<Alloc>::pointer;
using const_pointer = std::allocator_traits<Alloc>::const_pointer;
using reference = value_type&; // <-- here
using const_reference = const value_type&; // <-- here
using difference_type = std::allocator_traits<Alloc>::difference_type;
using size_type = std::allocator_traits<Alloc>::size_type;
class iterator;
};
template <typename T, typename Alloc = std::allocator<T>>
class container::iterator {
using value_type = std::allocator_traits<Alloc>::value_type;
using pointer = std::allocator_traits<Alloc>::pointer;
using const_pointer = std::allocator_traits<Alloc>::const_pointer;
using reference = value_type&; // <-- here
using const_reference = const value_type&; // <-- here
using difference_type = std::allocator_traits<Alloc>::difference_type;
using size_type = std::allocator_traits<Alloc>::size_type;
};
我是否必须像在示例中那样自己定义引用和 const_reference 类型,还是有另一种 std 方法?另一个问题是如何在不复制我的迭代器的情况下定义一个 const_iterator。
有人说我应该用值类型模板化我的迭代器,有些人只是写一个新的迭代器。
如果我要模板,我不知道我将如何为它创建正确的类型特征,所以我对 std:
reference operator*() const
和pointer operator->() const
,
因为的函数定义在技术上reference
将是const_reference
并且const_reference
将会是const const_reference
。
例如:
template <typename T>
class container {
template <typename ValueType>
class iterator;
using iterator = iterator<T>;
using const_iterator = iterator<const T>;
};
template <typename ValueType>
class container::iterator {
public:
using value_type = ValueType;
using pointer = value_type*;
using const_pointer = const value_type*;
using reference = value_type&;
using const_reference = const value_type&;
reference operator*() const;
pointer operator->() const;
};
解决方案
我是否必须像在示例中那样自己定义引用和 const_reference 类型
是的。分配器不知道您的容器是如何实现的,因此它不知道如何定义这些类型别名。
另一个问题是如何在不复制我的迭代器的情况下定义一个 const_iterator。
借助模板的魔力。iterator<T>
与iterator<const T>
。
因为 reference 是 const_reference 而 const_reference 在技术上是 const const_reference
这不是问题,因为 const 折叠规则就是const_reference
您想要的。const T&
const const_reference
const T&
推荐阅读
- cuda - CUDA中常量内存的配置和映射
- python - 如果我已经将模型作为泡菜,为什么我需要在 docker 容器中使用 sklearn?
- sql - 将代码移动到嵌套查询以解决复制粘贴问题
- java - 有没有办法在生产环境中启用 javax.naming.ldap 包的调试日志?
- html - 如何在 React Dashboard App 中创建复杂的布局
- c# - 在 Pivot 中包含更多行
- eclipse - 从cmd启动tomcat时如何在eclipse中进入调试模式
- c - Win32兼容windows操作系统的dll文件
- chart.js - 跳过折线图的初始动画
- .net - AutoCAD 插件程序集多个版本