在C ++中的switch语句中未处理所有枚举值时的编译时断言 [英] Compile-time assert when not all enum values are handled in a switch statement in C++

查看:58
本文介绍了在C ++中的switch语句中未处理所有枚举值时的编译时断言的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当未在switch语句中处理所有可能的枚举值时,我想得到编译器警告或错误.当然,我可以添加一个带有断言的默认案例,并(最终)在运行时得到一个错误.但是我想在编译时出错.

I'd like to get a compiler warning or error when not all possible enum values are handled in a switch statement. Of course I can add a default case with an assert and (eventually) get an error at runtime. But I'd like to get an error at compile-time.

我不确定C ++是否完全可以,但是也许有人知道一个窍门...

I'm not sure if this is possible at all with C++, but maybe someone knows a trick...

使用 -Wswitch 似乎是GCC的解决方案.VS2010有类似的东西吗?(我不使用GCC).

Using -Wswitch seems to be the solution for GCC. Is there something similar for VS2010? (I'm not using GCC).

Edit2:好的,我找到了VC ++(VS2010)的解决方案:

Ok, I found the solution for VC++ (VS2010):

启用警告 C4062 会在缺少值且未提供默认大小写的情况下发出警告.

Enabling warning C4062 produces a warning when a value is missing und no default case is provided.

启用警告 C4061 会在缺少值时发出警告,即使提供了默认情况也是如此.

Enabling warning C4061 produces a warning when a value is missing, even if a default case is provided.

推荐答案

您还没有提到您使用的是哪个编译器.如果您使用的是GCC,则只需启用 -Wswitch (由 -Wall 自动启用)即可免费获得.

You haven't mentioned which compiler you're using. If you're using GCC, you can get that for free simply by enabling -Wswitch (which is automatically enabled by -Wall).

这篇关于在C ++中的switch语句中未处理所有枚举值时的编译时断言的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆