1 #include "VariadicTemplates.h"
7 // Introduction to C++ Variadic Templates: https://kevinushey.github.io/blog/2016/01/27/introduction-to-c++-variadic-templates/
8 // Using Variadic Templates cleanly: https://florianjw.de/en/variadic_templates.html
9 // Variadic templates in C++ : https://eli.thegreenplace.net/2014/variadic-templates-in-c/
11 namespace VariadicTemplates
13 template <typename
... Ts
> // Template parameter pack: multiple types (0 type can be given).
14 void ignore(Ts
... ts
)
23 template <typename T
, typename
... Ts
>
24 double sum(T t
, Ts
... ts
)
26 return t
+ sum(ts
...);
39 template <typename T
, typename
... Ts
>
40 double power_sum(T t
, Ts
... ts
)
42 return t
+ power_sum(square(ts
)...);
52 cout
<< "Ctor" << endl
;
56 : a(other
.a
), b(other
.b
)
58 cout
<< "Copy ctor" << endl
;
61 // This move ctor isn't necessary because it does the same thing as the copy ctor.
63 : a(other
.a
), b(other
.b
)
65 cout
<< "Move ctor" << endl
;
72 ostream
& operator<<(ostream
& os
, const S
& s
)
74 os
<< "{ a = " << s
.a
<< ", b = " << s
.b
<< "}";
80 template<typename
... Ts
>
81 void ignore_return_values(Ts
&&...) {}
83 template<typename
... Ts
>
84 void increment_all(Ts
& ... values
)
86 ignore_return_values((++values
)...);
90 void VariadicTemplates::tests()
92 ignore(1, 2.0, true); // Types can be different.
94 cout
<< sum(1, 2, 3, 4) << endl
;
95 cout
<< power_sum(1, 2, 3, 4) << endl
;
100 // 'emplace_back' use variadic template.
101 v
.emplace_back(1, 1.5);
102 v
.emplace_back(2, 1.6);
103 v
.emplace_back(3, 1.7);
105 for (const auto& i
: v
)
106 cout
<< "element: " << i
<< endl
;
113 cout
<< i
<< ", " << d
<< endl
;