为什么我没有警告枚举比较不匹配
Why am I getting no warning for enum comparison mismatch?
考虑此代码:
typedef enum Type1
{
val11,
val12
} Type1;
typedef enum Type2
{
val21,
val22
} Type2;
Type1 type1 = val11;
if ( type1 == val22 )
std::cout << "foo";
Visual Studio 2015不会发出任何警告(即使使用/墙)。但是,type1
和val22
的类型不是相同的类型。这是正常的还是视觉工作室错误?
在比较不同类型的枚举时,编译器没有义务发出警告。我在标准中找不到它。对于经典的枚举类型,存在隐式类型转换为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;
}
相关文章:
- 不带大括号的枚举形式
- 枚举环境变量的惯用C++14/C++17方法
- 类似枚举的计算常量
- 如何正确实现和访问运算符的各种自定义枚举器
- 错误:从"int"到枚举c++的转换无效
- C++中构造函数中的枚举
- 标准::可选枚举的比较运算符
- 将用户值与枚举中的值进行比较
- 无法将返回的枚举与枚举进行比较
- 比较枚举的值会给出编译器错误
- C ++枚举可以与整数进行比较,但不能从整数分配?
- 比较枚举类值时的奇怪行为
- 为什么我没有警告枚举比较不匹配
- 将错误代码枚举与 std::error_code 进行比较
- 重新定义枚举的比较运算符
- 我是否正确地将枚举值与C++的"or"运算符进行比较?
- gtest枚举和对象之间的比较
- 将枚举与整数进行比较
- 比较枚举类型时出现逻辑错误
- 为什么我不能分配错误的枚举元素,但可以与错误的枚举元素进行比较?