使用可变参数模板创建静态数组 [英] Create static array with variadic templates
问题描述
有一个关于stackoverflow的答案(我似乎不再找到了),它演示了如何在C ++ 11中使用可变参数模板在编译时创建一个静态数组:
There was an answer on stackoverflow (which I can't seem to find anymore) which demonstrated how a variadic template can be used in C++11 to create a static array at compile time:
template <class T, T... args>
struct array_
{
static const T data[sizeof...(args)];
};
template <class T, T... args>
const T array_<T, args...>::data[sizeof...(args)] = { args... };
可以提供递归元函数来实例化 array _
有任何数量的参数,然后将在编译时复制到内部数组。
A recursive meta-function could be provided to instantiate array_
with any number of parameters, which will then be copied at compile time into the internal array. It's a useful way to create meta-functions for generating constant arrays at compile time.
但是,一个问题是它依赖于类模板参数 >以获取填充数组的实际值。这导致一个主要的限制:只有积分常数可以用作值模板参数。所以,你不能使用这种技术来生成自定义类型的数组。
However, one problem is that it depends on class template parameters to get the actual values to populate the array. This results in one major limitation: only integral constants can be used as value template parameters. So, you can't use this technique to generate arrays of custom types.
我试图想办法解决这个限制,但不能想出任何东西。有没有办法让这个技巧与非整数常数一起使用?
I tried to think of something to work around this limitation, but can't come up with anything. Is there any way to make this technique work with non-integral constants?
推荐答案
自定义类型(即类)实例,只要它们可以从整数类型(或任何其他类型可以作为非模板参数提供,这里我不打算枚举)构造。
Well, you can indeed populate a static array with custom types (i.e. classes) instances provided that they are constructable from integer types (or whatever other types one may provide as non template parameters and which I am not going enumerate here).
只需看看下面的例子,我相信这是很清楚自己解释:
Just take look at the example bellow, which I believe is clear enough to be self explaining:
#include <iostream>
template<typename T>
class my_class
{
public:
my_class(T)
{
//construct
}
void print_something()
{
std::cout << "something\n";
}
};
template<class C, class T, T ... args>
struct array_
{
static C data[sizeof...(args)];
};
template<class C, class T, T ... args>
C array_<C, T, args...>::data[sizeof...(args)] = {C(args)...};
int main()
{
array_<my_class<int> , int, 1, 200, 0, 42>::data[2].print_something();
}
注意:在GCC 4.6下编译得很好
Note: compiled just fine under GCC 4.6
这篇关于使用可变参数模板创建静态数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!