#include <iostream>
#include <bitset>
using namespace std;
//1.第一步:用来终止递归
void print1() {};
//2.第二步
template <typename T, typename... Types>
void print1(const T& firstArg, const Types&... args)
{
cout << firstArg << endl;
print1(args...);
}
void main()
{
print1(7.5, "hello", bitset<16>(377), 42,"I am Ty!");
system("pause");
}
结果:
Variadic Template: 是指数量不定,类型不定的模板,如上所示的print函数,可以看到接受了不同类型的参数,调用的函数就是拥有Variadic Template的函数。print1(7.5, “hello”, bitset<16>(377), 42,“I am Ty!”);运行的时候,首先会7.5作为firstArg,剩余部分就是一包,然后在函数内部,继续递归调用print函数,然后把"hello"作为firstArg, 其余的作为一包,一直递归直到一包中没有数据,调用边界条件的print(空函数)结束。
void foo(int &sum)
{
}
template<typename T,typename... Args>
void foo(int &sum,const T &t, const Args&... rest)
{
sum += t;
foo(sum,rest...);
}
void main()
{
int nsum = 0;
foo(nsum,1, 100,200,300);
cout << nsum << endl;
system("pause");
}
结果: