我希望做这样的事情:
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; ... }
但是我怎么定义吧?这样做没有想到递归技术.
我想要一种通用技术,以便我可以从类型包中键入任何特定类型,而不仅仅是示例中显示的两种类型.
解决方法
#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; }
或者像这样的东西.
#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,float> c; std::cout << typeid(c.var1).name() << " " << typeid(c.var2).name() << std::endl; }
http://liveworkspace.org/code/7de289f128e86eb6006f576cbaf98991