C++使用模板可变参输入一个数据包DEMO:
class ttt { public: int xxx = 111; }; 实现两个重载的模板: template <typename T> std::ostream & Print(std::ostream &o, const T& t) { return o << t<<std::endl; } template <typename T, typename ... Argus> std::ostream & Print(std::ostream &o, const T& t,const Argus&...arg) { o << t << std::endl; return Print(o,arg...); } 关键就在于对Print的调用 比如参数为cout,1,3,5 第一次:Print(cout,1,3,5) 第二次:Print(cout,3,5) 第三次:Print(cout,5) 所以第三次就会匹配到第一个函数,于是返回,函数调用结束。 /* *传递给标准库用的重载函数都要在类外定义,模板实例化的时候程序会在runtime时候会根据类型自动找到合适的函数去匹配 **/ ostream& operator<<(std::ostream &os, const ttt &t) { return os << t.xxx << std::endl; } ostream& operator<<(std::ostream &os, const ttt *t) { return os << t->xxx << std::endl; } int main() { int iNum = 1; float fNum = 1.223356; string strNum("1.333"); char *szNum = "1.444"; ttt t; ttt *pT = new ttt(); Print(cout, iNum, fNum,strNum.c_str(), szNum,t,pT,1215545); return 0; } }