【发布时间】:2017-07-23 16:11:29
【问题描述】:
#include <vector>
#include <iostream>
using namespace std;
int main()
{
vector<int> coll;
decltype(std::begin(std::declval<vector<int>>()))
pos_1 = coll.begin();
auto pos_2 = coll.begin();
cout << typeid(decltype(pos_1)).name() << endl;
cout << typeid(decltype(pos_2)).name() << endl;
}
我的编译器是 clang 4.0。输出是:
class std::_Vector_const_iterator<class std::_Vector_val<struct std::_Simple_types<int> > > class std::_Vector_iterator<class std::_Vector_val<struct std::_Simple_types<int> > >
这意味着:pos_1 = pos_2; 可以,而pos_2 = pos_1; 不行。
为什么在这种情况下std::begin() 总是返回const_iterator 而不是iterator?
【问题讨论】:
-
我猜这是因为你使用临时推断
pos_1的类型。它们只绑定到 const 引用和所有这些,这就是 const 发挥作用的地方。
标签: c++ c++11 iterator standards type-safety