相关疑难解决方法(0)

在列表初始化中缩小转换为bool - 奇怪的行为

考虑一下这段C++ 11代码:

#include <iostream>

struct X
{
    X(bool arg) { std::cout << arg << '\n'; }
};

int main() 
{
    double d = 7.0;
    X x{d};
}
Run Code Online (Sandbox Code Playgroud)

在初始化过程中,从double到bool的转换范围正在缩小x.根据我对标准的理解,这是错误的代码,我们应该看到一些诊断.

Visual C++ 2013发出错误:

error C2398: Element '1': conversion from 'double' to 'bool' requires a narrowing conversion
Run Code Online (Sandbox Code Playgroud)

但是,Clang 3.5.0和GCC 4.9.1都使用以下选项

-Wall -Wextra -std=c++11 -pedantic 
Run Code Online (Sandbox Code Playgroud)

编译此代码没有错误,也没有警告.运行程序输出1(不出意外).


现在,让我们深入到陌生的领域.

改变X(bool arg)X(int arg)和,突然间,我们从锵得到一个错误

error: type 'double' cannot be narrowed to 'int' in initializer list [-Wc++11-narrowing]
Run Code Online (Sandbox Code Playgroud)

海湾合作委员会发出警告

warning: …
Run Code Online (Sandbox Code Playgroud)

c++ standards-compliance narrowing c++11 list-initialization

24
推荐指数
1
解决办法
2245
查看次数