我不确定 Boost 在您的场景中是否可用,因此这里有一个解决方案,其中必须在预处理器序列中定义 enum。然后使用该序列构建枚举和相应的mpl::vector,我们计算vector 的元素是否以奇特的方式唯一。我们可能想先定义一个合适的is_unique 算法,但这应该可以。
#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;
}
如果将枚举定义更改为:
#define MYENUM ((FOO, 0))((BAR, 1))((BAZ, 2))((BAZZ, 2))
您将收到一条错误消息,说明static_assert failed "enum values not unique"。