c++ - 缩小转换为 MSVC 中的 bool 警告

标签 c++ visual-c++

编译这段代码时:

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 的值,即 truefalse .它不能包含其他值。

因为 A::member 实际上可以表示 B 的所有值,所以它不是缩小转换,所以警告是假的。

关于c++ - 缩小转换为 MSVC 中的 bool 警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54658122/

相关文章:

c++ - 在 MSVC 2017 中检测警告

c++ - mingw中发送信号的 "kill"函数在哪里?

c++ - MSVC 提示函数指针不是编译时常量

c++ - 从 C++ 程序启动 IE

c++ - 如何在 if 语句中使用 dynamic_cast

c++ - 当我解调它时,为什么这个 C++ 双端队列代码为 'less efficient'?

c++ - 在内部使用 try catch 防止 C++ DLL 异常

c++ - Visual C++ 2005 的奇怪链接问题

c++ - 错误 C1001 : An internal error has occurred in the compiler

C++ 错误 : Cannot convert 'Object' to 'Object*'