C++第09课 模板 (二)
1.可变参模板函数
//列表方式展开 template<class _Ty> void print(_Ty data) { cout << data << endl; } template<class ...Args> void printData(Args... args) { int array[] = { (print(args),0)... }; } //递归方式展开 void printData2() { cout << endl; } template<class _Ty,class ...Args> void printData2(_Ty data, Args ...args) { cout << data << "\t"; printData2(args...); } //求任意个整数的和 //1.递归展开 int sum() { return 0; } template<class _Ty,class ...Args> int sum(_Ty data, Args ...args) { return data + sum(args...); } //2.列表展开 template<class _Ty> _Ty sum2(_Ty data) { return data; } template<class ...Args> int sum1(Args... args) { int array[] = { (0,sum2(args))... }; int sum = 0; for (int i : array) { sum += i; } return sum; } int main() { printData(1, "love", 2.2f, 'A'); printData2(1, "love", 2.2f, 'A'); cout << sum(1, 2, 3, 4, 5) << endl; cout << sum1(1, 2, 3, 4, 5) << endl; return 0; }
2.可变参数模板类
//模板特化+递归的方式展开参数包 template <class ...Args> class Tup; //特化 template <> class Tup<> {}; //递归方式实现 template <class _Ty,class ...Args> class Tup<_Ty, Args...> { public: Tup(_Ty data, Args ...args) :data(data), args(args...) {} _Ty& head() { return data; } Tup<Args...>& next() { return args; } protected: _Ty data; Tup<Args...> args; }; void testTup() { Tup<int, string, char> tup(1, "string", 'A'); cout << "第一个参数:" << tup.head() << " 第二个参数:" << tup.next().head() << " 第三个参数:" << tup.next().next().head() << endl; Tup<string,int,int,int,int> mm("mm",18,98,88,88); } //模板特化+继承的方式展开参数包 template <class ...Args> class Test; template <> class Test<> { }; /* template <class _This, class... _Rest> class tuple<_This, _Rest...> : private tuple<_Rest...> */ template <class _Ty,class ...Args> class Test<_Ty, Args...> :public Test<Args...> { public: Test(_Ty data, Args... args) :data(data), Test<Args...>(args...) {} _Ty& head() { return data; } Test<Args...>& next() { return *this; } protected: _Ty data; }; void testTest() { Test<int, string, char> test(1, "string", 'A'); cout << "第一个参数:" << test.head() << " 第二个参数:" << test.next().head() << " 第三个参数:" << test.next().next().head() << endl; Test<string, int, int, int, int> mm("mm", 18, 98, 88, 88); } int main() { testTup(); testTest(); tuple<int, string, char> testTuple; return 0; }