Wednesday, March 28, 2012

Variadic templates

Every time, every time, C++ surprise me. Today, with variadic templates that allow us to specifier an unknown number of arguments. And this becomes an completely useful tool.

At the moment, I won't explain it because still being a mystery for me. Just say that this allow recursion
like prolog. Moreover, we can make containers of different types and even very things that I don't know.

Here's my example:


#include <iostream>

using namespace std;

//base case:
template<class T>
void printArray(T last){
     cout << last << endl;
}

template<class First, class...Rest>
void printArray(First first, Rest... rest){
     cout << first << ", ";
     printArray(rest...);
}

struct A{
public:
     string info;
public:
     A(string in) : info(in){};
     friend ostream& operator<<(ostream& out, const A& a){
         out << a.info;
         return out;
     };
};

int main(void){
     printArray(1);
     printArray(1,2);
     printArray(1,2,3);
     printArray(1,2,3,4,5);
     
     printArray("I");
     printArray("I","can't");
     printArray("I","can't","that");
     printArray("I","can't","that","this");
     printArray("I","can't","that","this","works");
     
     //diferent types, even a custom class
     printArray(1,"aloha",2.123,'a', A("Com estas?") );
     
     return 0;
}

Output:



1, 2, 3
1, 2, 3, 4, 5
I
I, can't
I, can't, that
I, can't, that, this
I, can't, that, this, works
1, aloha, 2, que tal?
1, aloha, 2.123, a, Com estas?



No comments:

Post a Comment