枚举类的编译时间索引器

问题描述 投票:0回答:1

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

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中工作。这可行吗?谢谢!

c++ c++11 templates template-meta-programming constexpr
1个回答
1
投票
#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

但是,请注意,此方法将枚举器value本身作为有效代码返回。

© www.soinside.com 2019 - 2024. All rights reserved.