2015-09-06 72 views
0

继从here代码:枚举失踪原因编译器错误

enum class OS_type { Linux, Apple, Windows }; 

const std::string ToString(OS_type v) 
{ 
    switch (v) 
    { 
     case Linux: return "Linux"; 
     case Apple: return "Apple"; 
     case Windows: return "Windows"; 
     default:  return "[Unknown OS_type]"; 
    } 
} 

我想删除default,而是迫使编译器生成错误,如果开关未完成了我的枚举。

回答

2

GCC /锵

您正在寻找-Wswitch-enum

时发出警告switch语句具有枚举类型的索引,并且 缺乏的情况下,为一个或多个列举的指定码。 枚举范围外的案例标签在使用 时也会引发警告。 -Wswitch和 选项之间的唯一区别是,即使存在默认标签,此选项也会提示有关省略的枚举代码 。

const std::string ToString(OS_type v) 
{ 
    // warning: enumeration value 'Windows' not handled in switch [-Wswitch-enum] 
    switch (v) 
    { 
     case OS_type::Linux: return "Linux"; 
     case OS_type::Apple: return "Apple"; 
     default:  return "[Unknown OS_type]"; 
    } 
} 

即使使用默认值,它抱怨缺少的Windows枚举。只需为Windows创建案例,并将默认值设置为忽略枚举值。

的Visual Studio

VS处理这种在编译器级别3和4,您需要启用警告C4061/C4062https://msdn.microsoft.com/en-US/library/96f5t7fy.aspx

+0

感谢,任何方式将此警告转换为错误? – barej

+1

查看'-Werror'。它在同一页面上列出。 – HelloWorld

相关问题