-
Notifications
You must be signed in to change notification settings - Fork 0
/
01-fold.cc
65 lines (56 loc) · 1.48 KB
/
01-fold.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
//
// Program
// Fold expression: Simple fold expression
//
// Compile
// g++ -Wall -Wextra -pedantic -std=c++17 -o 01-fold 01-fold.cc
//
// Execution
// ./01-fold
//
#include <iostream>
// Function accepts variadic arguments
// Keeps the return auto to accomodate different
// data types in the same function
template <typename ... Args>
auto add(Args ... args) {
return (args + ...);
}
template <typename ... Args>
auto add_2(Args ... args) {
return (args + ... + 0); // 0 is out identity element
}
//
// Entry function
//
int main() {
// Variadic template
{
// Above function will be expanded something like this
// for add(1, 2)
// int add<int, int>(int __ts0, int __ts1)
// {
// return __ts0 + __ts1;
// }
std::cout << "1 + 2 = " << add(1, 2) << '\n';
std::cout << "1 + 2 + 3 = " << add(1, 2, 3) << '\n';
std::cout << "1.0f + 2.0f = " << add(1.0f, 2.1f) << '\n';
std::string t1("Test1");
std::string t2("Test2");
std::cout << t1 << " + " << t2 << " = " << add(t1, t2) << '\n';
}
// no argument
{
// Following line will generate compiler error # unary fold expression has empty expansion
// for operator '+' with no fallback value return (ts + ...);
// std::cout << "1 + 2 + 3 = " << add() << '\n';
std::cout << " ... = " << add_2() << '\n'; // It will work
// because now compiler will generate something like following
// template<>
// int sum<>()
// {
// return 0;
// }
}
return 0;
}