为什么constexpr必须是静态的? [英] Why constexpr must be static?
问题描述
试图使用constexpr属性创建结构的成员而不是静态的尝试会导致编译器错误(请参见下文).这是为什么?对于单个常数值,我将在内存中保留该值,直到终止程序,而不仅仅是结构范围?我应该回到使用宏吗?
An attempt to create a member of a struct with constexpr attribute without being static result in a compiler error(see below). Why is that? for a single constant value will I have this value in memory until program is terminatted instead of just scope of struct? should I back to use a macro?
struct foo
{
constexpr int n = 10;
// ...
};
error: non-static data member cannot be constexpr; did you intend to make it static?
推荐答案
我不知道官方的合理性.但是可以肯定会导致混乱.我无法理解,非静态数据成员成为 constexpr
意味着什么.您能执行以下操作吗?
I don't know the official rational. But surely it could lead to confusion. I, for one, can't see what it means for a non-static data member to be constexpr
. Are you able to do the following?
struct foo {
constexpr int n = 10;
constexpr foo() { }
constexpr foo(int n):n(n) { } // overwrite value of n
};
还是这意味着初始化程序必须始终是常量,即不允许您编写以上内容(因为 n
不是常量/可能是非常量的),而是可以允许>
Or does it mean that the initializer must be constant always, i.e you are not allowed to write the above (because n
is not constant/could potentially non-constant) but allowed to say
foo f = { 10 };
constexpr int n
只是格式错误,而不是隐式地为 static
的规则对我来说似乎很好,因为IMO尚不清楚其语义.
The rule that constexpr int n
is simply ill-formed rather than being implicitly static
seems good to me, as its semantics would not be clear IMO.
这篇关于为什么constexpr必须是静态的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!