禁止隐式“无符号”到“双重”转换
Forbidding implicit `unsigned` to `double` conversion
是否可以禁止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++中,将大的无符号浮点数四舍五入为整数的最佳方法是什么
- 将无符号char*转换为std::istream*C++
- 如何在C++中将一个无符号的 int 转换为两个无符号的短裤?
- 从矢量<无符号字符>转换为字符* 包括垃圾数据
- 如何理解将半精度指针转换为无符号长指针和相关的内存对齐
- C++中无符号字符溢出
- 使用无符号字符数组有效存储内存
- 如何打印boost多精度128位无符号整数
- C++模板函数,用于比较任何无符号整数和有符号整数
- 在 std::无符号字符的向量处存储 int 的十六进制表示形式
- 获取隐式转换溢出从无符号到已签名的警告
- 如何在保持其值的同时将 c++ 无符号字符变量转换为 char 变量
- 从 std::vector<无符号字符>切片中提取 int?
- 是什么导致了这种使用三进制而不是短整型的有符号int到无符号int转换
- 无法在 Arduino 中uint8_t数组转换为无符号长整型数组
- 将无符号字符的向量存储在数组中会给我 std::bad_alloc
- 使用 fopen 打开 .pak 文件并使该文件应用于 const 无符号字符* (C++)
- C4018:类内有符号、无符号不匹配
- 隐式转换双重到无符号长溢出 c++
- 禁止隐式“无符号”到“双重”转换