【问题标题】:What is the difference between a static const and constexpr variable?静态 const 和 constexpr 变量有什么区别?
【发布时间】:2014-06-25 15:34:12
【问题描述】:

我知道 constexpr 变量 可以在编译时使用。 例如,对于模板或静态断言。

但如果我想在没有 constexpr 的情况下这样做,我可以使用 static const

自C++11/14引入constexpr有什么区别

constexpr int a = 3;
//AND
static const int a = 3;

谢谢!

查看此问题的另一种方法是我应该使用哪个?

【问题讨论】:

  • 这在很大程度上取决于您拥有声明的在哪里static 限定符在不同的地方做不同的事情。
  • constexpr 也适用于非ints。
  • @KerrekSB 值得,const 也是如此。
  • @R.MartinhoFernandes: struct Foo { static const double x = 1.5; };?

标签: c++ c++11 static-variables constexpr


【解决方案1】:

我知道的主要区别是,constexpr 的值必须在编译时知道,而 const static 可以在运行时分配。

const static int x = rand();

【讨论】:

  • 好的,所以对于我写的使用没有区别,这只是动态初始化变量(就像你第一次评估函数的范围)?
猜你喜欢
  • 2017-12-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-14
  • 2010-09-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多