C ++:确保枚举值在编译时是唯一的 [英] c++: ensure enum values are unique at compile time
问题描述
我有以下描述错误代码的枚举
:
I have the following enum
that describes error codes:
typedef enum {
et_general = 0,
et_INVALID_CLI_FLAG = 1,
...
et_undef = 500
} EErrorType;
我明确编写枚举值的主要原因是简化调试过程。
无论如何,我想知道是否有办法使编译器抱怨非唯一值。
我总是可以在运行时轻松检查它,但我想避免这种情况。
The main reason why I explicitly write the enum values, is to ease the debug process.
Anyways, I wonder if there's a way, to make the compiler complain about non unique values.
I can always check it at run time easily, but I'd like to avoid that.
我已阅读此帖子并查看了此 answer 。据我了解,该答案建议以这样的方式生成枚举: 更容易犯错误。
我想离开枚举
I've read this post and reviewed this answer. As I understand, that answer suggests to generate the enum in such way that it "make it much harder to make mistakes".
I'd would like to leave the enum definition as is, or close to it.
推荐答案
我不确定您的方案中是否可以使用Boost,所以这里是一种必须在预处理程序序列中定义 enum
的解决方案。然后,该序列用于构建枚举和相应的 mpl :: vector
,我们计算 vector
在奇特时尚中是独一无二的。我们可能想先定义一个合适的 is_unique
算法,但这应该可以。
I'm not sure if Boost is available in your scenario, so here is a solution where the enum
has to be defined in a pre-processor sequence. That sequence is then used to build the enum and a corresponding mpl::vector
and we compute if the elements of the vector
are unique in an odd-fashion. We might want to define a proper is_unique
algorithm first, but this should do.
#include <boost/mpl/vector.hpp>
#include <boost/mpl/int.hpp>
#include <boost/mpl/sort.hpp>
#include <boost/mpl/unique.hpp>
#include <boost/mpl/size.hpp>
#include <boost/preprocessor/tuple/elem.hpp>
#include <boost/preprocessor/seq/enum.hpp>
#include <boost/preprocessor/seq/transform.hpp>
#define MYENUM ((FOO, 0))((BAR, 1))((BAZ, 2))
#define GET_NAME(_, __, elem) BOOST_PP_TUPLE_ELEM(2, 0, elem) = BOOST_PP_TUPLE_ELEM(2, 1, elem)
#define GET_VALUE(_, __, elem) boost::mpl::int_<BOOST_PP_TUPLE_ELEM(2, 1, elem)>
enum E {
BOOST_PP_SEQ_ENUM(BOOST_PP_SEQ_TRANSFORM(GET_NAME, _, MYENUM))
};
typedef boost::mpl::sort<
boost::mpl::vector<
BOOST_PP_SEQ_ENUM(BOOST_PP_SEQ_TRANSFORM(GET_VALUE, _, MYENUM))
>
>::type evalues;
typedef boost::mpl::unique< evalues, boost::is_same<boost::mpl::_1, boost::mpl::_2> >::type uniqued;
static_assert(boost::mpl::size<uniqued>::value == boost::mpl::size<evalues>::value, "enum values not unique");
int main()
{
return 0;
}
如果将枚举定义更改为:
If you change the enum definition to:
#define MYENUM ((FOO, 0))((BAR, 1))((BAZ, 2))((BAZZ, 2))
您将收到一条错误消息,指出 static_assert失败的枚举值不唯一
。
you will get an error stating the static_assert failed "enum values not unique"
.
这篇关于C ++:确保枚举值在编译时是唯一的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!