枚举的元编程问题
Meta-programming problem with 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;
然后使用变量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;
时,您将实例化两个模板的顶部,然后当它变为零时,它将实例化专门化,并且只有最终结果将在运行时可见,因为模板在编译时解析
相关文章:
- C++模板编程设计问题 - 根据输入文件返回不同的类型
- Frank Luna 在他的书"使用 DirectX12 进行 3D 游戏编程"的介绍中盒子示例的问题
- 此动态编程问题的自上而下方法
- 返回不停止函数,递归函数问题?(编程练习,动态规划,Levenshtein 回溯)
- 寻找解决这个动态编程问题的提示
- 面临在 if 语句之外打印变量数据的问题 完成使用 Qt 编程
- 竞争性编程问题说错了答案
- 模板编程初学者问题
- 使用虚幻引擎4编程的平台游戏中的偏转问题
- 以编程方式锁定注册表项以避免并发问题
- 如何解决在使用动态 2D 数组进行矩阵乘法的 MPI 进行并行编程时的问题
- 编程:原理与实践 使用C++ 第 4 章演练步骤 6:关于数字范围的一般问题
- 我在用c ++编程时一直遇到LNK2005错误,我似乎无法弄清楚问题是什么
- 罗马数字C++编程转换问题
- 编程问题和概念
- 问题是关于C 的数组,以便在编程主题中有更多的了解
- Stroustrup的代码审查-编程原理-Ch-4-问题:3-错误:矢量下标超出范围
- 代码块上的编译器标志出现问题.编程初学者
- 由于基于接口的编程,遇到 C++ 虚拟模板函数问题
- 有没有更好的方法来解决这个问题 - 编程原理和实践使用C++:第 4 章 - 演练?