First commit
[cpp_sandbox.git] / Sandbox / FoldExpressions.cpp
1 #include "FoldExpressions.h"
2
3 #include <iostream>
4 using namespace std;
5
6
7 // Ep 20: https://www.youtube.com/watch?v=nhk8pF_SlTk
8 // https://en.cppreference.com/w/cpp/language/fold
9
10 namespace FoldExpressions
11 {
12 // Old fashion (before C++17).
13 template<typename ... T>
14 auto sum(T ... t)
15 {
16 typename common_type<T...>::type result{};
17 initializer_list<int>{ (result += t, 0)... };
18 return result;
19 }
20
21 // With C++17.
22 template<typename ... T>
23 auto sum2(T ... t)
24 {
25 const double n = 5;
26 return (5 + ... + t);
27 }
28
29 template<typename ... T>
30 auto avg(T ... t)
31 {
32 return (t + ...) / sizeof...(t);
33 }
34 }
35
36 void FoldExpressions::tests()
37 {
38 cout << sum(1, 2.2, 3, 4, 5) << endl;
39 cout << sum2(1, 2.2, 3, 4, 5) << endl;
40
41 cout << avg(1, 2.2, 3, 4, 5) << endl;
42 }