c++ - 禁止隐式 `unsigned` 到 `double` 转换

标签 c++ floating-point unsigned

是否可以禁止C++中基本类型之间的隐式转换?特别是,我想禁止从 unsignedfloatdouble 的隐式转换,因为存在以下错误:

int i = -5;
...
unsigned u = i; // The dawn of the trouble.
...
double d = u;   // The epicenter of the bug that took a day to fix.

我尝试过这样的事情:

explicit operator double( unsigned );

不幸的是,这不起作用:

explicit.cpp:1: error: only declarations of constructors can be ‘explicit’
explicit.cpp:1: error: ‘operator double(unsigned int)’ must be a nonstatic member function

最佳答案

您不能简单地从语言中完全删除隐式标准转换。

话虽如此,在某些情况下有一些方法可以防止意外的转换。在初始化期间,您可以使用大括号语法来防止缩小转换范围。浮点类型和整型类型之间的转换始终被视为缩小范围(编辑:除非源是整数常量表达式)。

int i {-5};       // ok; -5 fits in an int
unsigned u = i;   // ok; no check for narrowing using old syntax
double d {u};     // error: narrowing

如果您正在编写一个采用 double 的函数,您可以通过添加整型类型的重载然后删除它们来防止传递整型。

关于c++ - 禁止隐式 `unsigned` 到 `double` 转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35566235/

相关文章:

c++ - 谁能解释一下为什么两个 "results"不同?

c++ - 相同的算法实现在 Python 和 C++ 中有不同的结果?

floating-point - "bias value"是什么 float ?

c - printf 如何知道变量传递的是有符号还是无符号

c - 意外的无符号最大结果

c++ - 在 C++ 未定义行为中,是否从较小的无符号值中减去较大的无符号值?

c++ - 官方 ld 链接器规范

c++ - 扫描数字数组并计算范围 (0 - 24)(25 - 49) 等之间的数字的算法

在C中将纬度和经度转换为 float

javascript - 我如何在 webgl 中使用 stride?