GCC:禁止隐式布尔>整数转换
GCC: Forbid implicit bool->int conversion
是否有禁止隐式bool
到int
转换的gcc标志?
我想用这个代码得到任何警告:
void function( int value, bool flag ) { }
int main()
{
int a = 123;
bool flag = true;
//oops, a common mistake
function( flag, a );
}
作为一种变通方法,在C++11中,您可以删除其他可能的重载:
template <typename T> void function(int, T) = delete;
要回答您的问题:不,在这种情况下没有发出警告的gcc标志。你的问题在gcc邮件列表上讨论了好几次。例如:
编译器不检查这一点的主要原因在于,否则像if( intval )
这样的每个语句也会引发警告。
在C中,您可以将值包装在只支持一种类型的泛型选择中:
#include <stdbool.h>
#include <stdio.h>
bool x = true;
int y = _Generic(1, bool:2);
int main(void) {
printf("%dn", y);
}
这会出错(GCC 4.9),但如果将1
替换为true
或x
,则编译时不会出现任何问题。
举个例子:
#include <stdbool.h>
void function( int value, bool flag ) { }
#define function(V, F) function(V, _Generic(F, bool:F))
int main() {
int a = 123;
bool flag = true;
function( flag, a ); // error: '_Generic' selector of type 'int' is not compatible with any association
}
clang整洁会警告您,甚至更好的是,让这成为一个错误。
这方面的测试是可读性隐式布尔转换。在早期版本的linter中,该测试被命名为readability-implicit-bool-cast
。
使用包装类:
class Boolean
{
bool flag;
public:
explicit Boolean(bool something){}
bool getValue() const {return flag;}
void setValue(bool a) {flag = a;}
};
void function(int value,Boolean flag ) { }
int main()
{
int a = 123;
Boolean flag(true);
function( flag, a ); // fails! Boolean isn't a int value :)
}
使用kernel.h中问题min宏中的思想,可以使用gcc的typeof
#include <stdbool.h>
#define function(x, y) do {
__typeof(x) tmpone = (x);
int tmptwo = 0;
(void) (&tmpone == &tmptwo);
fx((x), (y));
} while (0)
void fx(int value, bool flag) {
(void)value;
(void)flag;
}
int main(void) {
int a = 123;
bool flag = true;
function(a, flag);
function(flag, a); // oops, a common mistake
}
相关文章:
- 如何反转整数参数包
- enum是C++中的宏变量还是整数变量
- 努力将整数转换为链表。不知道我在这里做错了什么
- 整数不会重复超过随机数
- 在C++中手动调整数组大小
- 检查输入是否不是整数或数字
- C++使用整数的压缩数组初始化对象
- 在C++中,将大的无符号浮点数四舍五入为整数的最佳方法是什么
- 将"打开的CV图像"中的"颜色"转换为整数格式
- 通过套接字[TCP]传输数据 如何在C / C ++中打包多个整数并使用send() recv()传输数据
- 如何只允许用户输入正整数
- 如何在c++中从文本文件中逐行读取整数
- C++:如何循环通过向量中的整数元素
- 我可以信任表示整数的浮点或双精度来保持精度吗
- 序列化,没有库的整数,得到奇怪的结果
- 在一定长度后从数组中打印时缺少整数
- std::当在256字节边界上写入整数时,流的奇怪行为
- 内联程序集printf将整数解释为地址
- 是否基于数组B整数打印数组A中的整数
- C :对矢量进行排序&lt; struct&gt;(结构有2个整数)基于结构的整数之一