可变参数模板
1,基础应用
#include<iostream> #include<string> #include<sstream> using namespace std; template<typename... Args> void g(Args... args) { cout<<sizeof...(Args)<<endl; //类型参数的数目 cout<<sizeof...(args)<<endl; //函数参数的数目 } template<typename T> string f(T t) { cout<<"f()"<<endl; ostringstream strm; strm<<t<<'-'<<t<<endl; cout<<strm.str(); return strm.str(); } template<typename T> ostream &print(ostream &os, const T &t) { cout<<"p1()"<<endl; return os<<t; } template<typename T, typename... Args> ostream &print(ostream &os, const T &t, const Args&... reset) { cout<<"p2()"<<endl; os<<t<<", "; //return print(os, reset...); return print(os, f(reset)...); } int main() { g(); g(1); g(1, 1.2); g(1, 1.2, "hello"); print(cout, 1, 3.4, "hello"); cout<<endl; return 0; }
重点理解其递归调用
2,