Friday, May 21, 2010

How to create a C++ tuple to take any amount of type

Boost C++ had a tuple library, which can take any amount of the type (maxium 10):

tuple<int>
tuple<double&, const double&, const double, double*, const double*>
tuple<A, int(*)(char, int), B(A::*)(C&), C>

The key is to use the default parameter type in a separated declaration:

namespace tuples{
//(1) A null Type will be refered as default template parameters
struct null_type {};

//(2) A class can take up to 3 class type
template<class T0, class T1, class T2>
class tuple{
public:
//(3) Constructor for these type
    tuple(T0 t){}
    tuple(T0 t0, T1 t1){}
    tuple(T0 t0, T1 t1, T2 t2){}
};

//(4) default parameter will take effect
template <class T0=null_type, class T1=null_type, class T2=null_type>  class tuple;

}

using namespace tuples;

int main()
{
  tuple<int> b(1);
  tuple<int, char> c(2,'a');
  tuple<int, float, char> d(3,12.5,'c');
}


No comments: