M3t*_*0it 6 c++ variadic-templates
我希望做这样的事情:
template<typename ...T> struct foo
{
bar<0 /*to index through types in pack*/ ,T...>::type var1;
bar<1 /*to index through types in pack*/ ,T...>::type var2;
...
}
Run Code Online (Sandbox Code Playgroud)
但是我该怎么定义bar?这样做没有想到递归技术.
我想要一种通用技术,以便我可以从类型包中键入任何特定类型,而不仅仅是示例中显示的两种类型.
#include <iostream>
#include <typeinfo>
template<class T, class T2, class... Args>
class C
{
public:
typedef T type1;
typedef T2 type2;
};
int main()
{
typedef C<int, double, int, float> c;
std::cout << typeid(c::type1).name() << " " << typeid(c::type2).name() << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
或者像这样的东西.
#include <iostream>
#include <typeinfo>
template<int N, class T, class... Args>
struct expand
{
public:
typedef typename expand<N - 1, Args...>::type type;
};
template<class T, class... Args>
struct expand<1, T, Args...>
{
public:
typedef T type;
};
template<class... Args>
class argsExpander
{
public:
typedef typename expand<1, Args...>::type type1;
typedef typename expand<2, Args...>::type type2;
};
template<class... Args>
class C
{
public:
typename argsExpander<Args...>::type1 var1;
typename argsExpander<Args...>::type2 var2;
};
int main()
{
C<int, double, int, float> c;
std::cout << typeid(c.var1).name() << " " << typeid(c.var2).name() << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
http://liveworkspace.org/code/7de289f128e86eb6006f576cbaf98991