1. 程式人生 > 實用技巧 >C++新特性__變參模板(Variadic Templates)

C++新特性__變參模板(Variadic Templates)

 1 #include <stdio.h>
 2 #include <iostream>
 3 #include <bitset>
 4 
 5 // 實現函式輸入任意引數
 6 template <typename T, typename... Types>
 7 void print(const T& firstArg, const Types&... args)
 8 {
 9     std::cout << firstArg << std::endl;
10     // 可以使用sizeof...()知曉變參的個數
11 std::cout << sizeof...(Types) << " "<<sizeof...(args)<<std::endl; 12 13 // 注意此處的...在args後面 14 print(args...); 15 } 16 // 最後一個遞迴函式入參為空,所以需要定義一個終止條件 17 void print() 18 { 19 } 20 21 int main() 22 { 23 print("hello",123, 1.233,std::bitset<32>(23)); 24 return
0; 25 }

輸出:

 1 // 利用變參模板實現繼承的遞迴,從而通過實現一個tuple
 2 template<typename... Values>  class Tuple;
 3 template<> class Tuple<> {}; //終止條件
 4 template<typename Head, typename... Tail>
 5 class Tuple<Head, Tail...>
 6     :private Tuple<Tail...>
 7 {
 8     typedef Tuple<Tail...> inherited;
9 public: 10 Tuple() {}; 11 Tuple(Head h, Tail... t) :m_head(h), inherited(t...) {} 12 Head head() { return m_head; } 13 inherited& tail() { return *this; } 14 private: 15 Head m_head; 16 };