2017-06-01 145 views
1

在下面的代码中,我使用static_cast将强类型enum转换为int。另一方面也是如此。但是如果演员int不在enum的范围内,它也可以工作。为什么是这个,为什么编译器没有捕获这个?为什么强制类型枚举编译为“不在枚举范围内”的int?

#include <iostream> 
#include <string> 

enum class Name {Hans, Peter, Georg}; // 0, 1, 2 

std::string getName(Name name) { 
    switch(name) { 
     case Name::Hans: return "Hans"; 
     case Name::Peter: return "Peter"; 
     case Name::Georg: return "Georg"; 
     default: return "not valid name"; 
    } 
} 

int main() 
{ 
    // Cast a Name to an int, works fine. 
    std::cout<< static_cast<int>(Name::Peter) <<std::endl; // 1 
    std::cout<< static_cast<int>(Name::Hans) <<std::endl; // 0 

    // Cast an int to a Name 
    std::cout<< getName(static_cast<Name>(2)) <<std::endl; // Georg 
    std::cout<< getName(static_cast<Name>(3)) <<std::endl; // not a valid name 
    // I would expect a compiler error/warning like i get here: 
    // std::cout<< static_cast<int>(Name::Hans + 4) <<std::endl; 
} 
+2

您认为编译器应该“抓住”这个基础的基础是什么?据我所知,C++标准不需要任何诊断。 – nwp

+0

为整数值的有效性添加检查会强加运行时开销。 – Bernard

+0

当我取消注释最后一行'不匹配'operator +'(操作数类型是'Name'和'int')'时,得到的错误与您的关于枚举范围的问题没有任何关系。 – Kevin

回答

0

一方面,人们常常用枚举表示位标志:

enum class FontFlags { bright=0x1, bold=0x2, blink=0x4 }; 

现在,他们希望这项工作:

FontFlags(int(FontFlags::bold) | int(FontFlags::blink)) 

但当然值是6,其“不可能。”

+0

强类型枚举(带'enum class')不支持'operator |'。 – Kevin

+0

@Kevin:已更新以解决该问题。 –

+0

虽然我认为这种做法有失败目的。如果您需要转换为“int”,然后才能获得枚举的“不可能”值,则不再有有效的枚举。 – Kevin