编译这段代码时:
enum B: bool { T = true };
struct A { bool member; };
void foo(const B b = T)
{
A a{b}; // warning here
}
void bar()
{
const B b = T;
A a{b};
}
MSVC 在 foo
中发出警告:
warning C4838: conversion from 'const B' to 'bool' requires a narrowing conversion
但是编译 bar
没问题。
这是一个proof
这是编译器错误还是预期行为?
最佳答案
narrowing conversion定义的相关部分在 C++17 [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.
在您的代码中,B
是一个无作用域的枚举,具有固定的基础类型 bool
。在 [dcl.enum]/8 它说:
For an enumeration whose underlying type is fixed, the values of the enumeration are the values of the underlying type
这意味着 B
的唯一可能值是 bool
的值,即 true
和 false
.它不能包含其他值。
因为 A::member
实际上可以表示 B
的所有值,所以它不是缩小转换,所以警告是假的。
关于c++ - 缩小转换为 MSVC 中的 bool 警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54658122/