【问题标题】:Why am I getting no warning for enum comparison mismatch? [duplicate]为什么我没有收到枚举比较不匹配的警告? [复制]
【发布时间】:2017-04-15 02:01:01
【问题描述】:

考虑这段代码:

typedef enum Type1
{
    val11,
    val12
} Type1;

typedef enum Type2
{
    val21,
    val22
} Type2;

Type1 type1 = val11;
if ( type1 == val22 )
    std::cout << "foo";

Visual Studio 2015 不会发出任何警告(即使使用 /Wall)。但是type1val22 不是同一类型。这是正常的还是 Visual Studio 的错误?

【问题讨论】:

  • 如果像 c# 这样的枚举只是由整数支持,所以如果在 c++ 中成立,它可能等同于 if (type1 == 1)
  • 这很正常。等式运算符的两边都转换为int
  • 编写现代 C++ 代码,使用enum class
  • 这里typedef是没用的,除非枚举定义也是用C编译的。
  • @HansPassant:这会触发编译警告/错误吗?您能否通过示例将其发布为答案?

标签: c++ visual-studio enums warnings


【解决方案1】:

据我所知,编译器在比较不同类型的枚举时没有义务发出警告。我在标准中找不到它。 对于经典枚举类型,存在到 int 的隐式类型转换,因此生成的代码是完全合法的。 从语义上讲,比较不同类型的枚举通常是不正确的,因此从 C++ 开始,我们有一个不允许隐式转换的作用域枚举构造。 (见下面的代码)。

#include <iostream>
using namespace std;

enum UE1 // This is an unscoped enumeration (since C)
{
    val11,
    val12
};

enum UE2 // This is an unscoped enumeration too
{
    val21, // have to use different names for enumeration constants
    val22
};

enum class SE1 // This is an scoped enumeration (since C++11)
{
    val1,
    val2
};

enum class SE2
{
    val1, // can use the same names for the constants
    val2  // because they are in the different scope
};

int main(int, char**)
{
    if (val11 == val22) // implicit conversion from an enum to int is available
        cout << "UE::val11 is equal to UE::val22" << endl;

    if (static_cast<int>(SE1::val1) == static_cast<int>(SE2::val1)) // have to apply explicit conversion
        cout << "SE1::val1 is equal to SE2::val1" << endl;

    if (SE1::val1 == SE2::val1) // error!!! Cannot make implicit conversions from a scoped enumeration.
        cout << "SE1::val1 is equal to SE2::val1" << endl;

    return 0;
}

【讨论】:

    猜你喜欢
    • 2022-06-10
    • 1970-01-01
    • 1970-01-01
    • 2017-09-21
    • 1970-01-01
    • 1970-01-01
    • 2022-03-30
    • 1970-01-01
    • 2019-10-24
    相关资源
    最近更新 更多