c – 如何从可变参数类型的包中获取特定类型?
发布时间:2020-12-16 03:44:45 所属栏目:百科 来源:网络整理
导读:我希望做这样的事情: templatetypename ...T struct foo{ bar0 /*to index through types in pack*/,T...::type var1; bar1 /*to index through types in pack*/,T...::type var2; ...} 但是我怎么定义吧?这样做没有想到递归技术. 我想要一种通用技术,以便
我希望做这样的事情:
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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |