Given the following :
template <typename T0,typename T1,typename T2 , typename T3 , typename T4>
class Tuple
{
private:
T0 v0;
T1 v1;
T2 v2;
T3 v3;
T4 v4;
public:
void f()
{
cout << v0 << "," << v1 << "," << v2 << "," << v3 << "," << v4 << endl;
}
};
I want to create a partial class with only two int
-s , then I must specialize like this:
class NullType { }; // create an empty class
template <typename T0, typename T1>
class Tuple<T0,T1,NullType,NullType,NullType >
{
private:
T0 v0;
T1 v1;
public:
void func()
{
cout << "i'm a specialization" << endl;
}
};
But this implementation would require me to do :
Tuple<int,int,NullType,NullType,NullType> b;
so that's pretty ugly :)
Is there another way to implement a partial specialization without defining another (empty) class so I can do that : Tuple<int,int> b1;
?
You can make T2 through T4 default template arguments and use void
instead of the empty NullType
class, e.g.:
template <typename T0,typename T1,typename T2=void , typename T3=void , typename T4=void> class Tuple { private:
T0 v0;
T1 v1;
T2 v2;
T3 v3;
T4 v4;
public:
void f()
{
cout << v0 << "," << v1 << "," << v2 << "," << v3 << "," << v4 << endl;
}
};
template <typename T0, typename T1> class Tuple<T0,T1,void,void,void > {
private:
T0 v0;
T1 v1;
public:
void func()
{
cout << "i'm a specialization" << endl;
} };
int main(int argc, char** argv) {
Tuple<int,int> myTuple;
myTuple.func();
return 0;
}
See here for working example.
EDIT: or, you could just use boost::tuple or std::tuple with C++11 :)
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