首页 > 解决方案 > Visual Studio 允许为 bool 传入枚举

问题描述

使用 VS 2019 并且我知道今天应该使用“枚举类”,但是我正在使用的代码库有很多以下面的样式 A 定义的枚举。问题是程序员(我)调用 DoSomething(...) 传递枚举而不是 bool 并且 VS 不会抱怨警告或错误。

我已经尝试提高警告级别,但 VS 仍然没有抓住它。没有重写很多代码,有什么方法可以强制 VS 将其视为错误?

typedef enum A {a1,a2} A;

enum class B {b1, b2};

void DoSomething(bool aBool){}

int main()
{
    DoSomething(a1); //compiler does NOT catches a1 is not of type bool
    DoSomething(B::b1); //compiler catches B::b1 is not of type bool
}

标签: c++visual-studio

解决方案


感谢您的建议。最好的解决方案是重构为“枚举类”。就我的情况而言,第二好的方法是使用 Clang-Tidy 来捕捉这个错误。我在项目属性->代码分析页面做了两处改动;

  1. 启用 Clang-Tidy。它的默认值为否 在此处输入图像描述
  2. 启用特定的 Clang-Tidy 选项。所有选项的列表在这里 在此处输入图像描述

我原来的帖子中的代码现在将在构建后显示一个警告,这是我最初所期望的。

int main()
{
    DoSomething(a1); //Warning readability-implicit-bool-conversion implicit conversion 'A' -> bool    
}

推荐阅读