禁止隐式“无符号”到“双重”转换

Forbidding implicit `unsigned` to `double` conversion

本文关键字:无符号 双重 转换 禁止      更新时间:2023-10-16

是否可以禁止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的函数,则可以通过为整型类型添加重载,然后删除它们来防止传递整型类型。