考虑代码
#include <iostream>
struct Foo
{
constexpr static int n = 42;
};
const int Foo::n; // note const, NOT constexpr
int main()
{
std::cout << Foo::n;
}
静态成员的定义与类内声明不同,即使用const
代替constexpr
。上面的代码是否合法,如果是,为什么?它用 gcc 和 clang 编译。如果我们分别在定义和声明中交换 const
和 constexpr
,它也会编译。我知道 constexpr
暗示了变量的 const
,但反之则不然。
我的两分钱,同时查看一些文档,如 that one .
实际上,它可能是有效的。
事实上,constexpr
和const
之间的区别主要在于它们的用途,但前者暗示后者是副作用。
还有一个更微妙的区别:constexpr
是一个说明符,而const
是一个类型限定符 .
特别是:
const’s primary function is to express the idea that an object is not modified through an interface
另一边:
constexpr’s primary function is to extend the range of what can be computed at compile time, making such computation type safe and also usable in compile-time contexts
或者更简洁来自here :
constexpr - specifies that the value of a variable or function can appear in constant expressions
不管怎样,它发生了:
constexpr in front of a variable definition [...] implies const
因此,尽管应该使用 constexpr
而不是 const
的原因很明确,并且每个人都倾向于记住:
constexpr is not a general purpose replacement for const (or vice versa)
事实上,使用 constexpr
你实际上是在说这个成员是隐式的 const
(而且你对如何定义该成员有一组更具体的约束).
无论如何,一旦定义,该成员只不过是具有 const
类型限定符(可用于常量表达式)的数据成员,这就是您在类中声明的内容。