C++11 的 auto 类型很方便,所以现在也需要一个 const_auto 类型。例如,假设 std::list<T> a; ,如果

auto p = a.begin();

具有 std::list<T>::iterator 类型,那么人们希望
const_auto p = a.begin();

std::list<T>::const_iterator 类型。不幸的是,C++11 似乎没有听说过 const_auto 。那么,如何才能以好的风格达到想要的效果呢?

(有关信息, a related question is asked and answered here. )

最佳答案

C++11 确实允许你写

const auto p = a.begin();

但是,这并不能满足您的要求。这使常规迭代器能够处理其值无法更改的非常量数据。

右侧 a.begin() 的类型由 a 的类型决定,而不是由左侧的任何内容决定。如果 a 是非常量,则将调用 a.begin() 的非常量版本。因此,您可以将 a 转换为 const& 然后使用它,或者您可以对 a 进行常量引用并使用它:
const auto& b = a;
auto p = b.begin();

但是,更简单的方法是使用新引入的 .cbegin() 和 .cend():
auto p = a.cbegin();

关于c++ - 如何实现 const_auto,因为 C++11 缺少它?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/17246424/

10-11 22:00
查看更多