为什么constexpr必须是静态的?

时间:2014-04-13 18:38:33

标签: c++ c++11 clang constexpr

尝试使用constexpr属性创建结构的成员而不是静态会导致编译器错误(参见下文)。这是为什么?对于单个常量值,我将在内存中使用此值,直到程序终止而不仅仅是struct的范围?我应该回去使用宏吗?

struct foo
{
  constexpr int n = 10;
  // ...
};

error: non-static data member cannot be constexpr; did you intend to make it static?

1 个答案:

答案 0 :(得分:12)

我不知道官方理性。但肯定会导致混乱。例如,我无法看到非静态数据成员对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的规则对我来说似乎不错,因为它的语义不太清楚IMO。