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?
Aucun commentaire:
Enregistrer un commentaire