获取参数个数
template <class... T>
void f(T... args)
{
cout << sizeof...(args) << endl; //打印变参的个数
}
f(); //0
f(1, 2); //2
f(1, 2.5, ""); //3
获取参数
递归获取
每次获取几个参数,取决于参数包前面有几个参数,并且调用的时候,参数数量必须是每次解包参数的倍数。
template <class T, class ...Args>
// 参数包前面只有一个参数,每次解包只需要解 1个即可。调用时 print(); print(1); print(1, 2); 等等都是可以的。
void print(T head, Args... rest)
// 参数包前面有两个参数,每次解包需要解 2个。 在调用的时候,参数个数必须是 2 的倍数。print(); print(1, 2); print(1, 2, 3, 4) 这些是正确的。
// print(1, 2, 3); 这个就是错误的,编译不通过。
void print(T head, T head2, Args... rest)
void print()
{
cout << "empty()" << endl;
}
template <typename T, typename ... Args>
void print(T head, T head2, Args ... args)
{
cout << "Head: " << head << ", " << head2 << endl;
print(args...);
}
int main()
{
cout << "print()" << endl;
print();
//cout << "print(1)" << endl;
//print(1);
cout << "print(1, 2)" << endl;
print(1, 2);
cout << "print(1, 2, 3, 4)" << endl;
print(1, 2, 3, 4);
}
递归求和
template<typename T>
T sum(T t)
{
return t;
}
template<typename T, typename ... Types>
T sum (T first, Types ... rest)
{
return first + sum<T>(rest...); // return first + sum(rest...); 也可以
}
sum(1,2,3,4); //10
逗号表达式展开
include <iostream>
#include <initializer_list>
using namespace std;
template <typename T>
void print(T t)
{
cout << "t: " << t << endl;
}
template <typename ... Args>
void expand(Args ... args)
{
int arr[] = {(print(args), 0)...};
cout << "arr: " << endl;
cout << sizeof(arr) << endl;
for (int i = 0; i < sizeof(arr) / sizeof(int); i++) {
cout << arr[i] << "\t" << endl;
}
}
template <typename F, typename ... Args>
void expand1(const F& f, Args&& ... args)
{
initializer_list<int>{(f(forward<Args>(args)), 0)...};
}
template <typename F, typename ... Args>
void expand2(const F& f, Args&& ... args)
{
initializer_list<int>{(f(forward<Args>(args)), 0)...};
}
int main()
{
expand(1, 2, 3, 4);
int a = 1, b = 2, c = 3, d = 4;
d = (a = b, c);
cout << d << endl;
cout << "expand1: " << endl;
expand1([](int i){cout << i << endl;}, 1, 2, 3);
cout << "expand2: " << endl;
expand2([](auto i){cout << i << endl;}, 1, 2.3, "haha");
}
参考:
泛化之美--C++11可变模版参数的妙用
https://www.cnblogs.com/qicosmos/p/4325949.html