Varying number of definitions in a variadic template class
I recently thought of a problem. Let's say there is a variadic template like this one:
template <typename... Types>
class example
{
//something
};
Now what I want to achieve is that when I create an object of example<int, double, float>
, this template instance will be compiled:
class example<int, double, float>
{
int int_array[5];
double double_array[5];
float float_array[5];
}
And when I create an object of example<char, long, myClass2, myClass3>
, this instance of the class template will be generated:
class example<char, long, myClass2, myClass3>
{
char char_array[5];
long long_array[5];
myClass2 myClass2_array[5];
myClass3 myClass3_array[5];
}
So basically, for each variadic list of template parameters, repeat an action for every of the type name passed. In my example, I declared a 5-element array for each type passed to the variadic template. The names don't have to be "type_array", it can be anything, as long as I can do an action (like declaring a variable) for each of the type passed.
Is that possible?
那么......我想你可以使用继承
#include <string>
#include <iostream>
template <typename T>
struct wrp
{ T a[5]; };
template <typename ... Ts>
struct example : public wrp<Ts>...
{ };
int main()
{
example <int, float, std::string> e0;
e0.wrp<int>::a[0] = 1;
e0.wrp<float>::a[0] = 1.1f;
e0.wrp<std::string>::a[0] = "1.11";
std::cout << e0.wrp<int>::a[0] << std::endl; // print 1
std::cout << e0.wrp<float>::a[0] << std::endl; // print 1.1
std::cout << e0.wrp<std::string>::a[0] << std::endl; // print 1.11
}
链接地址: http://www.djcxy.com/p/66896.html
上一篇: 指向成员作为可变参数的模板
下一篇: 变量模板类中定义的数量有所不同