多个typedef用于相同类型

use*_*367 1 c++ stl typedef

下面的代码是类初始化列表,它在Ubuntu标准包中提供.在这个迭代器和const_iterator中是相同类型的typedef.我只是想知道为什么我们希望为不同类型的迭代器使用相同的typedef?理想情况下,对于Iterator,它应该有typedef _E*迭代器.

// In the class initializer list:
namespace std 
{ 
  /// initializer_list 
  template<class _E> 
    class initializer_list 
    { 
    public: 
      typedef _E                value_type; 
      typedef const _E&         reference; 
      typedef const _E&         const_reference; 
      typedef size_t            size_type; 
      typedef const _E*         iterator; 
      typedef const _E*         const_iterator;
Run Code Online (Sandbox Code Playgroud)

PS:我无法想到合适的头衔,所以我给了这个头衔

Jos*_*eld 5

为了满足一个要求的容器,这两种类型iteratorconst_iterator必须存在.许多算法和许多代码都依赖于具有这两种类型的容器.但是,没有理由该iterator类型必须是非const(可变)迭代器.在这种情况下,他们已经决定,双方iteratorconst_iteratorconst(不变)迭代器.

他们有两个迭代器的原因const是因为他们显然不希望你能够更改其中的值initializer_list.

作为另外一个例子,看看std::setiteratorconst_iterator类型也都不断的迭代器.由于std::sets包含有序元素,如果您能够更改其内容,则std::set该顺序将无效.为了防止这种情况,两个迭代器类型都是不可变的.