C / C ++枚举:当检测多个项目映射到相同的值 [英] C/C++ enums: Detect when multiple items map to same value
问题描述
有没有编译时的方式到C / C ++枚举内检测/ prevent重复值?
Is there a compile-time way to detect / prevent duplicate values within a C/C++ enumeration?
美中不足的是,有哪些被初始化为显式值多个项目
背景:
我继承了一些C code,如以下内容:
I've inherited some C code such as the following:
#define BASE1_VAL (5)
#define BASE2_VAL (7)
typedef enum
{
MsgFoo1A = BASE1_VAL, // 5
MsgFoo1B, // 6
MsgFoo1C, // 7
MsgFoo1D, // 8
MsgFoo1E, // 9
MsgFoo2A = BASE2_VAL, // Uh oh! 7 again...
MsgFoo2B // Uh oh! 8 again...
} FOO;
的问题是,作为code增长&放大器;作为开发者添加更多的信息到 MsgFoo1x
组,最终还是超支 BASE2_VAL
。
这code最终会被迁移到C ++,所以如果有一个C ++ - (模板魔法)唯一的解决办法,这是确定 - 但与C工作和C ++是更好的解决方案。
This code will eventually be migrated to C++, so if there is a C++-only solution (template magic?), that's OK -- but a solution that works with C and C++ is better.
推荐答案
我想到一个奇怪的把戏,你可以做,以赶上这在编译时间,但它可能并不总是为你工作。通过MsgFoo2A前右侧插入一个标志枚举值开始。
I can think of one bizarre trick you can do to catch this at compile time, but it might not always work for you. Start by inserting a "marker" enum value right before MsgFoo2A.
typedef enum
{
MsgFoo1A = BASE1_VAL,
MsgFoo1B,
MsgFoo1C,
MsgFoo1D,
MsgFoo1E,
MARKER_1_DONT_USE, /* Don't use this value, but leave it here. */
MsgFoo2A = BASE2_VAL,
MsgFoo2B
} FOO;
然后添加一个文件来检查 MARKER_1_DONT_USE
不大于 BASE2_VAL
大于(或 MsgFoo2A
如果你喜欢)。
Then add a file to check that MARKER_1_DONT_USE
is not greater than BASE2_VAL
(or MsgFoo2A
if you like).
extern int IGNORE_ENUM_CHECK[MARKER_1_DONT_USE > BASE2_VAL ? -1 : 1];
几乎每一个编译器写过,如果MARKER_1_DONT_USE比BASE_2_VAL更大会产生错误。 GCC吐出:
Almost every compiler ever written will generate an error if MARKER_1_DONT_USE is greater than BASE_2_VAL. GCC spits out:
test.c:16: error: size of array ‘IGNORE_ENUM_CHECK’ is negative
这篇关于C / C ++枚举:当检测多个项目映射到相同的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!