sajas
sajas

Reputation: 1599

Specializing template for pointers

I want to specialice a template class to make it behave differently for pointers of type Base and all other pointer types. I tried it using enable if. But it's not working the way i want it. Can anyone tell me what to do about it. the code that i tried:

class Base
{
};

class Derived:public Base
{
};

class Non_base
{
};

template<class T,class Enable=void> class Vector
{
public:
    Vector()
    {
        cout<<"Constructor of Vector "<<endl;
    }
};



template<class T> class Vector<T*>
{
public:
    Vector()
    {
        cout<<"Constructor of Vector<T *> "<<endl;
    }
};



template<> class Vector<Base*>
{
public:
    Vector()
    {
        cout<<"Constructor of Vector<Base*> fully specialized"<<endl;
    }
};


//template<class T> class Vector<T *>:public Vector<Base *>
//{
//public:
//    Vector()
//    {
//        cout<<"Constructor of Vector<Base*> partially specilized"<<endl;
//    }
//};


template<class T> class Vector<T*,typename enable_if<is_base_of<Base,T>::value>::type>
{
    Vector()
    {
        cout<<"Constructor of Vector<Base*> partially specilized"<<endl;
    }
};

Upvotes: 1

Views: 487

Answers (1)

Potatoswatter
Potatoswatter

Reputation: 137770

When you add enable_if to a subset of an existing overload set, you usually need to add it to the remaining members as well. When some overloads are enabled, the others must be disabled, or there will be ambiguity.

template<class T> class Vector<T*,typename enable_if<!is_base_of<Base,T>::value>::type>
{
public:
    Vector()
    {
        cout<<"Constructor of Vector<T *> "<<endl;
    }
};

You don't need to add enable_if<!…> to the full specialization as it's already the best match of the set so there cannot be ambiguity.

Upvotes: 3

Related Questions