C++得可变参数模板,对参数进行了高度繁华,可以标识任意数目、任意类型的参数,语法为:在class或typename后面带上省略号。

#include <iostream>
#include <vector>
using namespace std;
template <class... T>
void f(T... args)
{
    cout << sizeof...(args) << endl; //打印变参的个数
}

int main() {
    f();        //0
    f(1, 2);    //2
    f(1, 2.5, "");    //3
    return 0;
}

1)声明一个包含0到任意个模板参数的参数包

C++可以使用递归函数的方式展开参数包,获得可变参数的每个值。通过递归函数展开参数包,需要提供一个参数包展开的函数和一个递归终止函数,例如:

#include <iostream>
#include <vector>
using namespace std;

// 递归终止函数
void print() {
    cout << "end" << endl;
}

// 展开函数
template<class T, class ...Args>
void print(T head, Args... args) {
    cout << head << " " << endl;
    print(args...);
}

int main() {
    print(1, 2, 3, 4);
    return 0;
}
1
2
3
4
end