我有这样的东西:
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/