情况1:
模板类型参数A和B
函数参数A和B
分别看:
sayHello<int,int>
此时template<typename A, typename …B>
A为int,B为int
sayHello<int, int>(3, 4, 5, 6, 7); 中的3, 4, 5, 6, 7
此时void sayHello(A t, B … args)
A为3,B为4, 5, 6, 7
所以v,此时为4, 5, 6, 7
举例2:
sayHello<int,int>
此时template<typename A, typename …B>
A为int,B为int
sayHello<int, int>(3, 4, 5, 6, 7); 中的3, 4, 5, 6, 7
此时void sayHello(B … args)
B为3, 4, 5, 6, 7
template<typename T>
void Print(T value)
{
cout << value << endl;
}
template<typename Head, typename... Rail>
void Print(Head head, Rail... rail)
{
cout << head << ",";
Print(rail...);
}
int main(int argc, char *argv[])
{
Print(1); // 输出:1
Print(1, "hello"); // 输出:1,Hello
Print(1, "hello", 'H'); // 输出:1,Hello,H
return 0;
}
求可变参数的个数:
sizeof…(rest);
可变参数递归展开:
求和
#include <iostream>
#include <iomanip>
#include <string>
#include "Test.h"
using namespace std;
template<typename T>
T sum(T a)
{
return a;
}
template<typename T, typename ...Args>
T sum(T head, Args ...args)
{
return head + sum(args...);
}
int main()
{
int x = sum(1, 2, 3, 4);
return 0;
}