1、用可变参模板实现打印多个值
// basic
template<typename T>
void print(T v)
{
std::cout << v << std::endl;
}
// variadic Template
template<typename T,typename... Types>
void print(const T& first, const Types&... args)
{
std::cout << first << ", ";
print(args...);
}
测试
print(1, 2, 3, 4, 5);
测试结果
2、用可变参模板实现多个数相加
// basic
template<typename T>
T sumUp(const T& v)
{
std::cout << "In sumUp Base" << std::endl;
return v;
}
template<typename T,typename... Types>
T sumUp(const T& first, const Types&... args)
{
std::cout << "In sumUp MAIn: count of arguments:"
<< sizeof...(Types) << std::endl;
return first + sumUp(args...);
}
测试
std::cout << sumUp(1, 2, 3, 4, 5,6, 7, 8, 9, 10) << std::endl;
测试结果