c++ - 为了使函数返回编译时常量值,模板中是否需要 constexpr const Type?

标签 c++ stl constants constexpr stdarray

在 C++ 中查看 std::array 的实现,我看到一些我无法完全理解的东西..

例如返回数组第一个元素的函数定义为:

constexpr const-reference
front() const noexcept
{.......}

其中 const-reference 被定义为 const value_type&,因此上面的整个表达式计算为 constexpr const value_type&。知道在某些情况下我们可能希望在编译时知道函数返回的值,我的问题是为什么他们在同一行上同时使用 constexprconstconst 不是多余的,因为我们已经说过我们将要返回一个 constexpr 吗?

最佳答案

so the whole expression above evaluates to constexpr const value_type&

不完全是:constexpr,对于一个函数/方法,意味着这个函数/方法可以在编译时执行(也),而不是返回值是constexpr .

my question is why are they using both constexpr and const on the same line? isn't the const redundant as it was already said that we are going to be returning a constexpr ?

它在 C++11 中是多余的。

constexpr 是在 C++11 中引入的,在 C++11 中,constexpr 方法也(必然)是一个 const方法。

这从 C++14 开始改变了(一个很好的解释 here )

因此,从 C++14 开始,consexprconst(对于方法)是解耦的,如您所见in cppreferencestd::array::front()const 版本是 constexpr(从 C++17 开始)。

关于c++ - 为了使函数返回编译时常量值,模板中是否需要 constexpr const Type?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62984448/

相关文章:

c++ - 防止舍入错误

c++ - 在类内的 union 内访问 map 会出现段错误

c++ - 在 Xcode 中检查 STL 容器

ios - 如何从 H 文件访问变量

c - 赋值 <指向常量数组的指针> = <指向数组的指针> : incompatible pointers

c++ - 返回 const 值的函数

c++ - QWeb引擎 : handling get and post requests when a runJavaScript is performed

c++ - 涵盖boost::trim并接受std::vector <std::string>的函数

C++ 矩阵组合

STL - 为什么STL的命名约定使用这么多前导下划线?