枚举 类 的编译时索引器

compile time indexer for enum classes

您将如何创建一种编译时索引器,给定一组枚举 类 能够正确创建唯一标识符。

Template<class... Args>
struct Indexer
{

template<class T>
Indexer(T value)
  {
  value_ = someconstexprfunction<T>(value, interDistance_);
  }

int enumInternalIndexCode() { /* ... */ };
int effectiveEnumCode() { /* ... */  }

static constexpr int enumDistance_ = 100;
int value_ = 0;
};

// Usage:
enum class A {a,b,c,d,e}; enum class B{ a1,b1,c1}; enum class C{z,y,q};
using MyIndexer = Indexer<A,B,C>;
MyIndexer(A::a) t1; // value_ == 0
MyIndexer(B::a1) t2; //value_ ==  100
MyIndexer(B::b1) t3; //value_ ==  101
MyIndexer(C::z) t4; //value_ ==  200
t4.effectiveEnumCode(); // returns 0 (first element of the enum)
t4.enumInternalIndexCode(); // returns 2 (third enum in the Arg list (0,1,2) )

理想情况下,这应该能够工作,或者至少在编译时执行哈希计算,更理想的情况是它应该在 C++11 中工作。这可行吗?谢谢!

#include <type_traits>
#include <cstddef>

template <typename T, typename... Ts>
struct Index;

template <typename T, typename... Ts>
struct Index<T, T, Ts...>
    : std::integral_constant<std::size_t, 0> {};

template <typename T, typename U, typename... Ts>
struct Index<T, U, Ts...>
    : std::integral_constant<std::size_t, 1 + Index<T, Ts...>::value> {};

template <typename... Args>
class Indexer
{
public:
    template <typename T>
    constexpr Indexer(T value)
        : _value(Index<T, Args...>::value * _enumDistance + static_cast<int>(value)) {}

    constexpr int enumInternalIndexCode() const { return _value / _enumDistance; }
    constexpr int effectiveEnumCode() const { return _value % _enumDistance; }
    constexpr int value() const { return _value; }

private:
    static constexpr int _enumDistance = 100;
    int _value = 0;
};

DEMO

但是请注意,这个returns枚举数本身就是一个有效代码。