参考:泛化之美–C++11可变模版参数的妙用
根据参考资料,简单验证了一下模板函数、模板类中总共4种情况。
4种情况的详细讲解直接看参考资料吧,大佬写的非常好,在这里本人就不瞎说了。
#include//用哪个就取消相应注释 #define func_recursion // 可变模板参数函数——递归法 //#define func_comma // 可变模板参数函数——逗号表达式法 //#define class_recursion // 可变模板参数类——递归法 //#define class_inherit // 可变模板参数类——继承法 #ifdef func_recursion template void outprint(last_type t) { std::cout << t << std::endl; } template void outprint(first_type t, rest_types...datas) { std::cout << t << std::endl; outprint(datas...); } #endif #ifdef func_comma template void outp(last_type t) { std::cout << t << std::endl; } template void outprint(rest_types...datas) { int temp[] = {(outp(datas),0)...}; } #endif #ifdef class_recursion template class type_show{ public: static void print_type() { first_type temp; std::cout << typeid(temp).name() << std::endl; type_show ::print_type(); } }; template class type_show { public: static void print_type() { last_type temp; std::cout << typeid(temp).name() << std::endl; } }; #endif #ifdef class_inherit template class type_show :public type_show { public: type_show() { first temp; std::cout << typeid(temp).name() << std::endl; // 在构造函数中输出被展开的类型名 } }; template class type_show { public: type_show() { last_types temp; std::cout << typeid(temp).name() << std::endl; } }; #endif int main() { #if (defined func_recursion) || (defined func_comma) outprint(1, 2, 3, "1234"); #endif #ifdef class_recursion type_show ::print_type(); #endif #ifdef class_inherit // 连续继承时构造函数的执行顺序是倒着的 type_show temp; #endif system("pause"); }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)