Initializing a constexpr with a const, — int vs float

做~自己de王妃 提交于 2019-12-19 12:24:35

问题


I'm wondering why the integer ii is initiallized at compile time, but not the float ff here:

int main() {
  const int i = 1;
  constexpr int ii = i;

  const float f = 1.0;
  constexpr float ff = f;
 }

This is what happens when I try to compile:

> g++ -std=c++11 test.cc
test.cc: In function ‘int main()’:
test.cc:6:24: error: the value of ‘f’ is not usable in a constant expression
   constexpr float ff = f;
                        ^
test.cc:5:15: note: ‘f’ was not declared ‘constexpr’
   const float f = 1.0;

回答1:


Constant variables of integral types with constant initializers are integral constant expressions (de facto implicitely constexpr; see expr.const in ISO C++). float is not an integral type and does not meet the requirements for constant expression without the use of constexpr. (A similar case is why int can be but float cannot be a template parameter.)




回答2:


In C++ constant integers are treated differently than other constant types. If they are initialized with a compile-time constant expression they can be used in a compile time expression. This was done so that array size could be a const int instead of #defined (like you were forced in C):

(Assume no VLA extensions)

const int s = 10;
int a[s];          // OK in C++


来源:https://stackoverflow.com/questions/34665079/initializing-a-constexpr-with-a-const-int-vs-float

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!