C++ 常量和非常量容器的自定义迭代器

C++ Custom iterator for both const and non const container

本文关键字:常量 自定义 迭代器 非常 C++      更新时间:2023-10-16

我想为树实现一个自定义树类型(类似stl)和一个自定义迭代器。正如我对标准库的理解,任何容器只有 4 种类型的迭代器(常量/非常量、反向/非反向的组合),并且 const 是指它所持有的数据,而不是容器本身。

出于某种原因,在我的迭代器类中,我具有树类型的属性(我需要返回对它的 const 正确引用),这迫使我在用户创建 const 容器时使用不同的类型。

template <typename T> class tree;
template <typename T> class node;
template <typename T, typename Tree = tree<T>, typename Node = node<T>>
class iterator_base : public std::iterator<std::bidirectional_iterator_tag, T> {
protected:
    Tree *tree;
    Node *current_node;
public:
    Tree& get_tree() const {
        return *tree;
    }
    //...
};

是否可以对const treetree使用相同的迭代器类型?

基本上你应该

能够使用以下版本的迭代器:

typedef iterator_base<T, tree<T>, node<T> > iterator;
//either use T or const T for const_iterator (depends on your definition
//of const correctness in this case.
typedef iterator_base<T, const tree<T>, const node<T> > const_iterator;

唯一缺少的是从迭代器到const_iterator的隐式转换(可以使用template_if或通过子类化并仅指定这些成员来完成。如果使用const T则可能需要其他帮助程序函数将tree<T>转换为const tree<const T>

注意:此方法仅在迭代器上没有直接修改树/节点的特殊非常量成员时才有效(此类方法将/不应该在const_iterator上工作)