#include <iostream> // 使用模板参数包定义变长模板 void Print(){} template<typename FirstArg, typename... Args> void Print(FirstArg first, Args... args) { std::cout<<first<<std::endl; Print(args...);// 递归调用Print模板,若参数为空时调用上面非模板函数 } int main() { Print("hello", "world", 20, true); /* Print<char const*, char const*, int, bool>("hello","world", 20,true); Print<char const*, int, bool>("world", 20,true); Print<int, bool>(20,true); Print<bool>(true); Print(); */ return 0; } // 变参模板函数重载,若两个函数模板区别只在于尾部的参数包的时候,会优先选择没有尾部参数报的那个函数模板 template<typename T> void Printf(T arg){ std::cout<<arg<<std::endl; } template<typename FirstArg, typename... Args> void Printf(FirstArg first, Args... args){ Printf(first); // 会调用上面没有尾部参数包的模板函数 Printf(args...); } // 一个模板函数也可以达到上面同样效果,使用到sizeof...(args) template<typename FirstArg, typename... Args> void PrintArgs(FirstArg first, Args... args){ std::cout<<first<<std::endl; if constexpr (sizeof...(args)>0) { PrintArgs(args...); } else std::cout<<std::endl; } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45