c++ - 枚举的元编程问题

标签 c++ dynamic enums

我有这样的东西:

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;

然后使用变量来 访问所有值 <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,我觉得这就足够了。

关于c++ - 枚举的元编程问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7248774/

相关文章:

检查是否分配了内存中的某个地址

mysql - 将 grails/groovy 枚举映射到 Mysql 枚举

c++ - 模板特化和从其他模板类继承模板类

php - 循环遍历前十个数据库条目的通知系统

c++ - 模板循环依赖问题

具有动态表单的 Django FormWizard

java - 在枚举类型上实现 `next` 和 `previous` 的最佳方法是什么?

java - org.hibernate.HibernateException : Error while accessing enum. 值() : class com. mksoft.fbautomate.domain.Account$Type

c++ - thrust::sort_by_key 上的无效配置参数

c++ - 当我在 C++ 控制台应用程序中打印出超过 7 个控制台输出时,为什么我的 PC 会发出蜂鸣声?