gpt4 book ai didi

c++ - g++ 警告标志以避免 bool 到 double 转换

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:21:36 25 4
gpt4 key购买 nike

我寻找 g++ 的警告编译标志,它会阻止从 bool 到 double 的静默转换。

This answer涉及将 int 转换为 double 的更广泛问题。这个问题在那里被驳回了,因为它被认为是无损转换并且完全合法。但是,由于 bool 具有不同于简单整数的另一种语义含义,我希望从 bool 到 double 的隐式转换会发出警告。

我试过:
-Wall -Wextra -pedantic -Wconversion在以下代码上没有任何成功(没有发出警告):

#include <iostream>

int foo(double var){
return static_cast<int>(var);
}

int main(){
std::cout << foo(5) << std::endl;
std::cout << foo(5.1) << std::endl;
std::cout << foo(false) << std::endl; // here I want the warning
return 0;
}

我使用 g++ 4.9.2,但是建议使用更高版本的答案是完全可以接受的。
谢谢。

最佳答案

这是一种与 gcc 无关的方法,而是依赖于另一个工具:clang-tidy 有一个 readability-implicit-bool-conversion检查在这种情况下会警告你。您需要一个单独的静态分析检查(这可能需要很长时间才能运行,具体取决于您的代码库),但它有效:

clang-tidy --checks=readability-implicit-bool-conversion your-file.cpp

产量

[...] warning: implicit conversion bool -> 'double' [readability-implicit-bool-conversion]  

std::cout << foo(false) << std::endl; // here I want the warning
^~~~~
0.0

关于c++ - g++ 警告标志以避免 bool 到 double 转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57653560/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com