Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid specialization for a "big" template class without creating an empty class?

Tags:

c++

templates

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; ?

like image 888
JAN Avatar asked Jan 15 '23 17:01

JAN


1 Answers

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 :)

like image 50
Moritz Avatar answered Jan 31 '23 01:01

Moritz