variadic templates
main.cpp
Go to the documentation of this file.
1 // Variadic function
2 // see https://kubasejdak.com/variadic-functions-va-args
3 
4 #include <cstdarg>
5 #include <iostream>
6 using namespace std;
7 
8 // Variadic function (no constexpr possible)
9 int sum1(int count, ...)
10 {
11  int sum = 0;
12  va_list args;
13  va_start(args, count);
14 
15  for (int i = 0; i < count; ++i) {
16  int num = va_arg(args, int);
17  sum += num;
18  }
19 
20  va_end(args);
21  return sum;
22 }
23 
24 // Variadic template (constrexpr ist only an add on)
25 // special function to stop recursion
26 template <typename T>
27 constexpr auto sum2(T arg)
28 {
29  return arg;
30 }
31 
32 // general recursive function
33 template <typename T, typename... Args>
34 constexpr auto sum2(T first, Args... args)
35 {
36  return first + sum2(args...);
37 }
38 
39 // main test code
40 int main()
41 {
42  auto p1 = sum1(4, 6, 7, 8, 9);
43  cout << p1 << endl;
44 
45  auto p2 = sum2( 6, 7, 8, 9);
46  cout << p2 << endl;
47 
48  auto p3 = sum2( 6, 7, 8, 9.1);
49  cout << p3 << endl;
50  return 0;
51 }
52 /*
53  g++ -pedantic -std=c++17 -Weffc++ -Wall -Wextra -pedantic -Wswitch-default -Wfloat-equal -Wundef -Wredundant-decls -Winit-self -Wshadow -Wparentheses -Wshadow -Wunreachable-code -Wuninitialized -Wmaybe-uninitialized *.cpp
54  cppcheck --enable=all --inconclusive --std=c++11 --std=posix --suppress=missingIncludeSystem *.cpp
55  clang++ -std=c++17 -fsyntax-only -Wdocumentation -Wconversion -Wshadow -Wfloat-conversion -Wno-shorten-64-to-32 -Wno-sign-conversion -pedantic *.cpp
56  clang++ -std=c++17 -Weverything -Wno-c++98-compat -Wno-shorten-64-to-32 -Wno-sign-conversion -Wno-padded *.cpp
57  clang++ -cc1 --help
58  icpc -std=c++17 -Wall -Wextra -pedantic *.cpp
59 */
int sum1(int count,...)
Definition: main.cpp:9
int main()
Definition: main.cpp:40
constexpr auto sum2(T arg)
Definition: main.cpp:27