Variadic templates and tuples

Working with tuples and variadic templates

Someday I will try to explain the meaning of this, but I reckon its kind of self explanatory. This just prints out the tuples as they are, no big deal.

 1: 
 2: template<typename... T>
 3: struct Apa
 4: {
 5: 
 6:   explicit Apa(T... t): tups_(t...)
 7:   {
 8: 
 9:   }
10: 
11:   constexpr size_t contains() const
12:   {
13:     return sizeof...(T);
14:   }
15: 
16: 
17: 
18:   template<typename... Q>
19:   friend std::ostream& operator<<(std::ostream&, const Apa<Q...>&);
20: 
21: 
22:   std::tuple<T...> tups_;
23: };
24: 
25: 
26: template<typename... T>
27: Apa<T...> make_Apa(T... t)
28: {
29:   return Apa<T...>(t...);
30: }
31: 
32: 
33: template<class Tuple, std::size_t N>
34: struct TuplePrinter {
35:   static void print(std::ostream& os,const Tuple& t) 
36:   {
37:     TuplePrinter<Tuple, N-1>::print(os,t);
38:     os << ", " << std::get<N-1>(t);
39:   }
40: };
41: 
42: template<class Tuple>
43: struct TuplePrinter<Tuple, 1> {
44:   static void print(std::ostream& os, const Tuple& t) 
45:     {
46:       os << std::get<0>(t);
47:     }
48: };
49: 
50: template<class... Args>
51: void print(std::ostream& os, const std::tuple<Args...>& t)
52: {
53:   TuplePrinter< decltype(t),sizeof...(Args)>::print(os,t);
54: }
55: 
56: 
57: 
58: 
59: 
60: template<typename... Q>
61: std::ostream& operator<<(std::ostream& os, const Apa<Q...>& apa)
62: {
63: 
64:   print(os,apa.tups_);
65: 
66:   os << "Hej" << '\n';
67:   return os;
68: }
69: 
70: 
71: 
72: int main()
73: {
74: 
75:   int x=1,y=2,z=3;
76: 
77: 
78:   auto apa = make_Apa(x,y,z,2.345,"fisk");
79:   std::cout << " " << apa <<"\n";
80:   return 0;
81: }
82: 

Lämna ett svar

E-postadressen publiceras inte. Obligatoriska fält är märkta *