Initializing constexpr with const: Different treatment for int and double

允我心安 提交于 2019-12-03 11:40:20

Shafik Yaghmour already provided a link explaining the background.

Since I have to maintain code which has to compile with different standards, I use the following macro:

#if __cplusplus <= 199711L  // lower than C++11
  #define MY_CONST const
#else // C++11 and above
  #define MY_CONST constexpr
#endif
straceX

Rule:"constexpr must be evaluate at compile time".

Let's look below code (generic example);

    const double k1 = size_of_array(); 

k1 is constant, the value of its initializer is not known compile time but its initializer is known until run time so k1 is not constant expression. As a result a const variable is not constexpr.

But compiler see these code:

    const int k1 = 10;  
    constexpr int k2 = 2*k1;

One exception occurs. A constexpr integral value can be used wherever a const integer is required, such as in template arguments and array declarations [1].

You can get extra information from the links below:

  1. Constexpr - Generalized Constant Expressions in C++11
  2. const vs constexpr on variables | stackoverflow
  3. Difference between constexpr and const | stackoverflow
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!