首页 > 解决方案 > 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*() constpointer 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;
};

标签: c++containersc++17typetraitsconst-iterator

解决方案


我是否必须像在示例中那样自己定义引用和 const_reference 类型

是的。分配器不知道您的容器是如何实现的,因此它不知道如何定义这些类型别名。

另一个问题是如何在不复制我的迭代器的情况下定义一个 const_iterator。

借助模板的魔力。iterator<T>iterator<const T>

因为 reference 是 const_reference 而 const_reference 在技术上是 const const_reference

这不是问题,因为 const 折叠规则就是const_reference您想要的。const T&const const_referenceconst T&


推荐阅读