2013-02-11 79 views
1

我想专门研究一个模板类,使它对Base类型的指针和所有其他指针类型的行为有所不同。我尝试使用启用if。但它不是我想要的方式。任何人都可以告诉我该怎么做。 ,我试图代码:指针专用模板

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

回答

3

当您添加enable_if到现有重载集合的子集,通常需要将其添加到剩余的成员。当一些重载被启用时,其他的必须被禁用,否则会有歧义。

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

你并不需要添加enable_if<!…>充分专业化因为它已经设定所以不能有歧义的最佳匹配。

+0

当我试图为模板函数做同样的事情时,我得到一个错误:重新声明模板类,这似乎是正确的。我宣布了一个函数来接受指针,并且在一个函数中我检查了它是否是Base类型,而在另一个中我检查了它是否是基类型。但是这两个函数都有相同的论点。如何避免它? – sajas 2013-02-11 09:45:27

+0

嗯,不知道你在描述什么。也许再开一个问题。 – Potatoswatter 2013-02-12 03:05:24