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
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?
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.
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.
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, ...);.
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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With