Thursday, March 29, 2012

Playing with variadic

Okey, here's an example with variadics. Of course, that's not ever the best way, in fact, it's absolutely bad practice but I was just playing with.

So, if you are interested in what this guy did? go ahead if not and you want to learn and even use
some of my ideas, don't try it.

Being weighed, this is not a good example, just take it for fun.


#include <iostream>

template<typename...Types>
class List{
public:
     int size;
     void** elements;//aray of things
     List(){
         size = sizeof...(Types);
     };
     List(Types... Args){
         size = sizeof...(Types);
         elements = new void*[size];
         if(size != sizeof...(Args) )
             std::cout << "diferent size" << std::endl;
         else{
             std::cout << "good" << std::endl;
             push(0,Args...);
         }
     };
    
private:
     template<class T>
     void push(int pos, T last){
         if(pos == size-1){
             std::cout << "at: " << pos << " added -> " << *last << std::endl;
             std::cout << "All correct" << std::endl;
             elements[pos] = static_cast<void*>(last);
         }
     }
     template<class First, class...Rest>
     void push(int pos, First first, Rest...rest){
         elements[pos] = static_cast<void*>(first);
         std::cout << "at: " << pos << " added -> " << *first << std::endl;
         pos++;
         push(pos,rest...);
     }
};

using namespace std;

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){
     List<int*,int*,double*,string*,A*> list(new int(1),new int (2),
                     new double (2.101), new string("aloha"),new A("NICE") );

     cout << "size: " << list.size << endl;
     cout << *static_cast<int*>(list.elements[0]) << ", ";
     cout << *static_cast<int*>(list.elements[1]) << ", ";
     cout << *static_cast<double*>(list.elements[2]) << ", ";
     cout << *static_cast<string*>(list.elements[3]) << ", ";
     cout << *static_cast<A*>(list.elements[4]) << ", ";
     
     return 0;
}

Output:


good
at: 0 added -> 1
at: 1 added -> 2
at: 2 added -> 2.101
at: 3 added -> aloha
at: 4 added -> NICE
All correct
size: 5
1, 2, 2.101, aloha, NICE,

No comments:

Post a Comment