用const, - int vs float初始化一个constexpr [英] Initializing a constexpr with a const, -- int vs float

查看:182
本文介绍了用const, - int vs float初始化一个constexpr的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道为什么整数 ii 在编译时初始化,而不是float ff 这里:

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;


推荐答案

>积分常数表达式(事实上暗示 constexpr ;请参见ISO C ++中的expr.const)。 float 不是一个整数类型,并且不满足常量表达式的要求,而不使用 constexpr 。 (类似的情况是为什么 int 可以但 float 不能是模板参数。)

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.)

这篇关于用const, - int vs float初始化一个constexpr的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆