禁止隐式“unsigned”到“double”的转换

Forbidding implicit `unsigned` to `double` conversion

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