这段代码:
std::vector <int> ints(5,1);
std::for_each(ints.begin(), ints.end(), [](const decltype(*std::begin(ints))& val){ val*=2; });
在 Visual Studio 2010 中编译和运行得很好,并且修改容器中的每个值,就像没有 const 关键字一样。这是编译器中的错误吗,因为预期的行为是 val 是不可修改的? (换句话说,我希望它不会编译,但它会编译)
更新:
std::for_each(ints.begin(), ints.end(), [](const std::remove_reference<decltype(*std::begin(ints))>::type& val){ val*=2; });
似乎常量行为正确,但这并没有让我变得更聪明。
注意:
decltype(*std::begin(ints))
是对 int 的引用。
最佳答案
编译器似乎试图将 const
应用于 int&
,使其成为 int& const
,这是多余的无论如何都无法重新设置引用1)。尝试将 const 放在 decltype
和引用之间:decltype(*ints.begin()) const&
1)感谢评论的澄清。
废话,感谢@Ben 的评论,我注意到了真正的问题。试试 decltype(*ints.cbegin())
。 cbegin
返回一个 const_iterator
,它取消对常量引用的引用。此外,不需要额外的符号,因为 *ints.cbegin()
已经返回一个 int const&
。
为了解释 OP 的代码出了什么问题,正如 @Ben Voigt 在评论中所说:decltype(*std::begin(ints))
解析为 int&
,因为 std::begin(ints)
返回非常量容器的非常量迭代器,并且取消引用这样的迭代器会返回对非常量的引用。
关于c++ - const decltype(*std::begin(container))& val 不会使 val const?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8166837/