包含重复值的C ++ 11枚举类 [英] C++11 Enum class containing duplicate values
问题描述
经典的C ++枚举没有简单的方法来检测重复值。
The classic C++ enums don't have a straight forward method to detect duplicate values.
新C ++ 11中的此问题是否已解决枚举类
?
Is this issue addressed in the new C++11 enum class
?
enum class ConnectionState : uint32_t
{
Connecting,
Reconnecting = 2,
Disconnecting,
LocalConnection,
NoNetwork = 2,
WifiNetwork,
Last
}
推荐答案
当前无法检测或阻止一个枚举中的多个相同枚举值枚举。
There is currently no way to detect or prevent multiple identical enum values in an enum.
反射工作组正在研究如何向语言中添加反射(C ++代码自省C ++代码的能力)。在反射所涵盖的一长串内容中,有一个简短的列表正在处理,在那个短列表中,可以检查编译时枚举的值。
The reflection working group is working on how to add reflection -- the ability for C++ code to introspect C++ code -- to the language. In the long list of stuff that reflection covers, there is a short list being worked on, and in that short list, examining the values of an enumeration at compile time is there.
N4428 contains a proposal for enum reflection. There are some partial implementations out there.
根据N4428,检测重复项将很容易。您可以在编译时获得枚举值的数量及其值。只需按顺序创建所有枚举值的包,然后测试它们是否唯一。然后将该测试的结果放入 static_assert
。
Under N4428, detecting duplicates would be easy. You can get the number of enumeration values, and their value, all at compile time. Simply create a pack of all the enum values in order, and test that they are unique. Then toss the result of that test into a static_assert
.
最终结果可能是:
template<class E>
constexpr bool all_values_unique(); // todo
static_assert( all_values_unique<ConnectionState>(), "Duplicate enum value detected" );
在将反射提案添加到C ++之前,这是不可能的。
Prior to something like that reflection proposal being added to C++, this is not possible.
您可以使用宏来伪造它-具有一个既可以创建枚举又可以创建反射特性信息的宏-然后编写 all_values_unique
使用反射特征信息。这样做的好处是,如果/当标准和/或编译器获得所需的反射功能时,可能很容易剥离宏。
You can fake it using macros -- have a macro that both creates your enum and creates reflection traits information about it -- then write all_values_unique
that uses the reflection traits information. This has the advantage that if/when the standard and/or your compiler gets the reflection features needed, it may be easy to strip out your macros.
这篇关于包含重复值的C ++ 11枚举类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!