c++ - 通用统一初始化 : `double` to `int`

标签 c++ c++11 visual-c++ c++14 list-initialization

Visual Studio 2015 更新 3.C++11\C++14。

对于 int:

constexpr int ci1 {50};
constexpr int ci2 {500};

char c1 {ci1}; // OK
char c2 {ci2}; // compilation error

通用统一初始化可以在编译模式下检查值(从intchar)。 Bjarne Stroustrup 在他的书中提到了这个案例。

我预计这对于 doubleint 的情况是正确的,但它不适用于 Visual Studio 2015 Update 3:

constexpr double cd {4.0};
int i1 {cd}; // compilation error

错误信息:

C2397 conversion from 'double' to 'int' requires a narrowing conversion

这是正确的行为(对于我的第二个代码示例)还是特定于 Visual Studio?

最佳答案

doubleint转换总是被认为是缩小的,这就是 Bjarne Stroustrup 创建 narrow_cast<> 的原因在他的书中实现了这种转换。

关于c++ - 通用统一初始化 : `double` to `int` ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38676274/

相关文章:

c++ - 我可以在要用 Qt Linguist 翻译的字符串中使用 "\n"字符吗

C++ unordered_map 使用自定义类类型作为键

c++ - 如何使用 AWS S3 C++ SDK TransferManager DownloadFile 回调

c++ - 用分配的最后一个值覆盖数组?

c++ - std::tuple_size 和部分专用模板

c++ - 将项目附加到 vector 会复制所有先前的项目

c++11 - 将 std::vector 扩展到参数包中

c++11 为 std::deque 或 std::list move 插入

c++ - 如何从汇编代码中找出函数原型(prototype)?

visual-c++ - MFC MessageBox 不显示在所有窗口的顶部