g ++警告标志,以避免布尔转换为两倍

mik*_*raf 4 c++ compilation g++

我正在寻找g ++的警告编译标志,该标志将阻止从bool到double的无声转换。

这个答案涉及一个更广泛的将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;
}
Run Code Online (Sandbox Code Playgroud)

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

lub*_*bgr 5

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

clang-tidy --checks=readability-implicit-bool-conversion your-file.cpp
Run Code Online (Sandbox Code Playgroud)

产量

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

std::cout << foo(false) << std::endl; // here I want the warning
                 ^~~~~
                 0.0
Run Code Online (Sandbox Code Playgroud)

  • 感谢您提供信息丰富的答案。我会再等一天看看是否有正确的 g++ 答案。如果没有,我会接受你的作为最有帮助的。 (2认同)