禁止隐式`unsigned`到'double`转换

Mic*_*ael 2 c++ floating-point unsigned

是否有可能禁止C++中基本类型之间的隐式转换?特别是,我想禁止隐式转换unsignedfloat或者double因为这些错误:

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.
Run Code Online (Sandbox Code Playgroud)

我试过这样的事情:

explicit operator double( unsigned );
Run Code Online (Sandbox Code Playgroud)

不幸的是,这不起作用:

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
Run Code Online (Sandbox Code Playgroud)

Bri*_*ian 5

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

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

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
Run Code Online (Sandbox Code Playgroud)

如果您正在编写一个带有a的函数,则double可以通过为整数类型添加重载来阻止传递整数类型,然后删除它们.