begin() 如何知道要返回哪种返回类型(常量或非常量)?

Art*_*hur 6 c++ iterator stl std

这完美地工作:

list<int> l;
list<int>::const_iterator it;
it = l.begin();
list<int>::iterator it2;
it2 = l.begin();
Run Code Online (Sandbox Code Playgroud)

我不明白的是如何list“知道”它必须返回iterator begin()版本或版本const_iterator begin() const

我正在尝试为我的容器(trie)实现迭代器,但我遇到了这个问题。难道 C++ 不应该通过返回类型来处理微分(除非使用奇怪的技巧)?

这是我得到的一些代码和编译器错误:

MyTrie<T>是一个可以包含任何类型的模板化树。我有一个Trie<int>::iter非常量迭代器和一个Trie<int>::const_iter常量迭代器。iter begin()const_iter begin() const在 Trie 类中声明(和定义)。

Trie<int> t;
Trie<int>::const_iter it;
it = t.begin();
Run Code Online (Sandbox Code Playgroud)

错误 :

../test/trie.cpp:181: error: no match for 'operator=' in 'it = Trie<T>::begin() [with T = int]()'
[..path..]/Trie.h:230: note: candidates are: Trie<int>::const_trie_iterator& Trie<int>::const_trie_iterator::operator=(const Trie<int>::const_trie_iterator&)
Run Code Online (Sandbox Code Playgroud)

所以,我相信begin不使用非常量版本。

我考虑operator=(const Trie<T>::const_trie_iterator&)为非常量迭代器创建一个方法,但我在STDlib 中没有看到它,我必须 const_cast 迭代器。我该怎么办?

Dav*_*eas 6

在标准容器中,非常量迭代器可以隐式转换为 const_iterator。返回的类型仅基于begin()被调用的对象/引用的常量性,在您的情况下是iterator,有一个转换允许以后的分配。

特别是在 23.2.1 一般容器要求,表 96 中,它说X::iterator必须可以转换为X::const_iterator.