Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ variadic template sum

Tags:

c++

c++11

I am trying to understand the C++11 feature called "variadic". Look at this simple code:

#include <iostream>

using namespace std;

template<typename T, typename... Args>
T adder(T first, Args... args) {
  return first + adder(args...);
}

int main() {

  int c = adder(1,8,4);
  cout << c << endl;

  cout << "Hello World!" << endl;
  return 0;

}

Readig the c++ primer book I have understood that they work in recursive way and I also see that in the recursive call the args... part is passed.

I am using MinGW 5 and QtCreator to test this. Look

enter image description here

Ok, to fix the Too few arguments I could call adder(first, args...) but now the recursion is not proper and the program crashes. What to do? I cannot understand how to do this.


Looking online I've found an example like this

template <typename T, typename... Rest>
double sum(T t, Rest... rest) {
  return t + sum(rest...);
}

It's basically the same. Do I have to put an explicit (non template) return type?

like image 461
Raffaele Rossi Avatar asked Dec 22 '17 12:12

Raffaele Rossi


People also ask

What is Variadic template in C++?

Variadic templates are class or function templates, that can take any variable(zero or more) number of arguments. In C++, templates can have a fixed number of parameters only that have to be specified at the time of declaration.

What is the use of Variadic templates?

With the variadic templates feature, you can define class or function templates that have any number (including zero) of parameters. To achieve this goal, this feature introduces a kind of parameter called parameter pack to represent a list of zero or more parameters for templates.

Is printf Variadic function?

Variadic functions are functions (e.g. printf) which take a variable number of arguments. The declaration of a variadic function uses an ellipsis as the last parameter, e.g. int printf(const char* format, ...);.

What is parameter pack in c++?

Parameter packs (C++11) A parameter pack can be a type of parameter for templates. Unlike previous parameters, which can only bind to a single argument, a parameter pack can pack multiple parameters into a single parameter by placing an ellipsis to the left of the parameter name.


1 Answers

You need the "stop-recursion-case" (do not know the correct name now; UPDATE: it's called "base-case", thanks Quentin) with just one argument when the template function is unfolding.

#include <iostream>

template<typename T>
T adder(T first) {
  return first;
}

template<typename T, typename... Args>
T adder(T first, Args... args) {
  return first + adder(args...);
}

int main() {
  const int c = adder(1, 8, 4);
  std::cout << c << '\n';
  return 0;
}
like image 165
Christian G Avatar answered Oct 06 '22 01:10

Christian G