尝试创建具有 constexpr 属性的结构成员而不是静态会导致编译器错误(见下文)。这是为什么?对于单个常量值,我是否会将这个值保留在内存中,直到程序终止,而不仅仅是结构的范围?我应该重新使用宏吗?
struct foo
{
constexpr int n = 10;
// ...
};
error: non-static data member cannot be constexpr; did you intend to make it static?
我不知道官方的理由。但它肯定会导致混乱。就我而言,我看不出非静态数据成员是
constexpr
意味着什么。下面的事情你能做到吗?
struct foo {
constexpr int n = 10;
constexpr foo() { }
constexpr foo(int n):n(n) { } // overwrite value of n
};
或者这是否意味着初始化器必须始终是常量,即不允许您编写上述内容(因为
n
不是常量/可能不是常量),但允许说
foo f = { 10 };
constexpr int n
只是格式错误而不是隐式static
的规则对我来说似乎很好,因为它的语义在我看来并不明确。