定义常量数组用作模板形参
Define constant array to use as template parameters
我正在寻找常量(n)的定义,允许它们在模板构造函数中用作参数,例如。像这样:
const int n[5] = { 4, 8, 16, 32, 64 };
for (int i = 0; i < 5; i++)
{
SomeClass<n[i]> C;
(...other things depending on n[i])
}
someeclass看起来像
template<int n> class SomeClass {...}
是否有任何方法(使用宏或其他任何东西)?
是的,您可以通过使用递归模板执行循环并将n
指定为constexpr
来做到这一点。这只适用于c++ 11或更高版本。工作示例(ideone link):
#include <type_traits>
template <int n>
class SomeClass
{
// debug function for example
public:
void debug() {
cout << "SomeClass<" << n << ">" << endl;
}
};
constexpr int n[5] = { 4, 8, 16, 32, 64 };
template <int i>
struct loop
{
static void doit()
{
SomeClass<n[i]> C;
C.debug();
// other things depending on n[i]
loop<i+1>::doit();
}
};
// close out the iteration
template <>
struct loop<std::extent<decltype(n)>::value>
{
static void doit()
{
}
};
int main() {
loop<0>::doit();
return 0;
}
输出:SomeClass<4>
SomeClass<8>
SomeClass<16>
SomeClass<32>
SomeClass<64>
这是不可能的for
循环。原因很简单:循环中的n[i]
不是一个常量表达式。i
可以在循环中以不同的方式进行更改,并且有关是否实例化SomeClass
的特定实例或其他实例的信息取决于运行时。
你可以使用模板元编程来代替:
template <int from, int to>
struct for_ {
template<template<int> class Fn>
static void run() {
Fn<from>::run();
for_<from + 1, to>::template run<Fn>();
}
};
template <int to>
struct for_<to, to> {
template<template<int> class Fn>
static void run() {}
};
然后,我们可以定义自己的实用程序:
template <int n>
struct SomeClass {};
constexpr int n[5] = { 4, 8, 16, 32, 64 };
template<int i>
struct functor {
static void run() {
SomeClass<n[i]> c;
// something else
}
};
,并将其用作:
int main() {
for_<0, 5>::run<functor>();
return 0;
}
现场演示
相关文章:
- 使用mem_fun_ref if成员函数需要多个形参
- 通过类的模板形参特化成员模板结构
- 非类型引用形参/实参
- 哪个模板形参在boost::shared_ptr构造函数中使用一个原始指针
- 如何确保迭代器模板形参与模板类的模板形参具有相同的数据类型
- 如何在编译时通过模板形参默认值的名称/指针获取函数的类型
- c++:候选模板被忽略:模板形参显式指定的参数无效
- c++中作为形参的指针
- 哪种方法更适合为函数提供编译时间常数?函数实参与模板形参
- 包含void*结构的函数的Const正确性和形参
- 传递boost::函数,该函数接受一个模板实参作为默认为NULL的形参
- 将右值引用形参强制转换为右值引用
- 给引用形参赋值使对象无效
- 当实参是初始化列表而形参是引用时,重载解析
- const整型模板形参的条件
- 定义常量数组用作模板形参
- c++形参是一个指向常量对象的指针,但不返回更新后的对象
- 为什么标准不允许在模板形参列表中初始化依赖于常量的类型
- c++使用constexpr函数的形参作为模板的常量
- 对具有相同形参类型但具有不同常量限定符的std::vector进行强制转换