c++ - 为什么 const int 适合 char 大括号 init?

标签 c++ c++11 constants narrowing

我认为大括号初始化不允许缩小。但为什么 char 大括号初始化允许使用 int const 呢?

int value1 = 12;
char c1{value1};  // error! no narrowing

const int value2 = 12;
char c2{value2};   // why is this fine?

查看on Godbolt .

最佳答案

const int value2 = 12;

value2 是一个编译时常量。编译器可以轻松(并且必须)证明该值是 12,它恰好在 char 表示的值范围内。

int value1 = 12;

value1 不是编译时常量。变量的值可能会在运行时更改。

标准规则的确切措辞(引用最新草案,强调部分已添加):

[dcl.init.list]/7

A narrowing conversion is an implicit conversion

  • from an integer type or unscoped enumeration type to an integer type that cannot represent all the values of the original type, except where the source is a constant expression whose value after integral promotions will fit into the target type.

关于c++ - 为什么 const int 适合 char 大括号 init?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57855180/

相关文章:

c++ - 在 bitset 中随机选择 set bit 位置的最佳 C++ 方法

c++ - 模板或类中的 static_assert,明白了

c++ - 如何绘制所有面都具有不同纹理的立方体?

c++ - #if 条件区域可以跨越包含文件边界吗?

c++ - Qt 两个类互相访问

c++ - 为什么这让我得到一个指向 const 对象字段的非常量指针?

c++ - 如何实现编译时字符串转换函数?

c++ - 自定义 QComboBox

objective-c - 接受原语的 Objective C 中的可变参数函数

c++ - 静态常量字符指针及其以这种方式使用的原因