Detect when multiple enum items map to same value

后端 未结 8 2157
猫巷女王i
猫巷女王i 2020-11-28 13:44

Is there a compile-time way to detect / prevent duplicate values within a C/C++ enumeration?

The catch is that there are multiple items which are initialize

8条回答
  •  春和景丽
    2020-11-28 14:08

    While we do not have full on reflection, you can solve this problem if you can relist the enumeration values.

    Somewhere this is declared:

    enum E { A = 0, B = 0 };
    

    elsewhere, we build this machinery:

    template
    struct first_not_same_as_rest : std::true_type {};
    template
    struct first_not_same_as_rest : std::integral_constant< bool,
      (s0 != s1) && first_not_same_as_rest< S, s0, s... >::value
    > {};
    
    
    template
    struct is_distinct : std::true_type {};
    
    template
    struct is_distinct : std::integral_constant< bool,
      std::is_distinct::value &&
      first_not_same_as_rest< S, s0, s... >::value
    > {};
    

    Once you have that machinery (which requires C++11), we can do the following:

    static_assert( is_distinct< E, A, B >::value, "duplicate values in E detected" );
    

    and at compile time we will ensure that no two elements are equal.

    This requires O(n) recursion depth and O(n^2) work by the compiler at compile time, so for extremely large enums this could cause problems. A O(lg(n)) depth and O(n lg(n)) work with a much larger constant factor can be done by sorting the list of elements first, but that is much, much more work.

    With the enum reflection code proposed for C++1y-C++17, this will be doable without relisting the elements.

提交回复
热议问题