使用Enum参数的c ++ c99模板特化,不使用integral_constant

时间:2014-03-17 22:49:29

标签: c++ templates c++11 enums template-specialization

基本上,我正在尝试使用可以执行位操作的枚举,并且有一个模板函数可以将枚举元素映射到数组索引。在我需要的操作员过载功能 编译时常量表达式。

我需要像integral_constant这样的东西,但是在c11中没有在c99中有人知道如何在c99中实现integral_constant吗?

OR

创建枚举的任何其他方法都可以执行位操作并索引数组吗?

感谢〜

enum E
{
  E_a=1,
  E_b=2,
  E_c=4,
  E_d=8,
  E_MAX=16,
};

// Template struct to compute the index 
template<int N>
struct I
{
  static const int idx = 1 + I<N/2>::idx;
};
template<>struct I<1>{ static const int idx= 0; };

// 
class Data
{
  static void Init()
  {
    data[E_a].value = 10;
    data[E_b].value = 20;
    data[E_c].value = 40;
    data[E_d].value = 80;
  }

  Data* operator[](const E& e)
  {
    return &(Data::data[I<e>::idx]); // <-Here is the problem, template parameter should be a constant expression but e is a parameter, even it is constant it is not a expression
  }
  // member variables
  void* value; 
  static Data data[I<E_MAX>::idx];
};

0 个答案:

没有答案