首页 > 解决方案 > begin() 在 C++17 中是 constexpr 而在 C++14 中是 cbegin() 吗?

问题描述

根据cppreferencestd::cbegin()对于容器是在 C++14 中引入的constexpr- 但是std::begin(),在 C++11 中引入的,直到 C++17 之前仍然是非常数的。

真的吗?这似乎很不平衡。这是什么原因?

标签: c++iteratorcontainersc++14c++17

解决方案


过载

template< class T, std::size_t N >
constexpr T* begin( T (&array)[N] ) noexcept;

在 C++14 中是 constexpr,所以在 C++14std::cbegin中调用std::begin的 也是 constexpr。

对于非数组,std::cbegin在 C++14 中的常量表达式中不可用,即使函数模板仍标记为constexpr.


推荐阅读