是否可以禁止C++中基本类型之间的隐式转换?特别是,我想禁止从 unsigned
到 float
或 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.
我尝试过这样的事情:
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/