枚举的元编程问题

Meta-programming problem with Enums

本文关键字:问题 编程 枚举      更新时间:2023-10-16

如果我有这样的东西:

template<int n>
struct Pow
{
  enum{val= Pow<n-1>::val<<1};
};
template<>
struct Pow<0>{
    enum{val =1};
};

我可以访问像Pow<30>::val这样的数据。这很好,但我想这样做

   int main()
    {
    Pow<30>::val;

然后使用变量to访问所有值<0,30>我知道我可以使用数组和动态规划,但我可以这样做吗?英语不好,

使用c++ 0x可变模板:

template<int... Indices>
struct powers {
    static const int value[sizeof...(Indices)];
    typedef powers<Indices..., sizeof...(Indices)> next;
};
template<int... Indices>
const int powers<Indices...>::value[sizeof...(Indices)] = { Pow<Indices>::val... };
template<int N>
struct build_powers {
    typedef typename build_powers<N - 1>::type::next type;
};
template<>
struct build_powers<1> {
    typedef powers<0> type;
};

然后:

int
main()
{
    // we want [0..30] inclusive so pass 31 as exclusive upper limit
    typedef build_powers<31>::type power_type;
    // 0..30 is 31 powers in all
    typedef const int array_type[31];
    array_type& ref = power_type::value;
    // ref[0] .. ref[30] are the values of Pow<0>::val .. Pow<30>::val
}

这是在没有动态初始化的情况下使用数组。由于您希望将结果作为变量而不是TMP,因此我认为这已经足够了。

当您执行Pow<30>::val;时,您将实例化两个模板的顶部,然后当它变为零时,它将实例化专门化,并且只有最终结果将在运行时可见,因为模板在编译时解析