2010-02-28 131 views
1

我有一个tempated基类检查和公开派生类childcheck。基类也有一个部分特殊化,但我从一般模板类继承了子类检查类(而不是从类检查的局部特化)。当我打电话从派生类的初始化列表基类的构造函数,编译器会发出错误,现在如果我删除类检查的部分特则编译器会发出任何错误,所以这里是代码
模板和继承问题!

#include<iostream.h> 
template<class t> 
class check 
{ 
t object; 
public: 
check(t element); 
}; 
template<class t> 
check<t>::check<t>(t element) 
{ 
cout<<"base class constructor"<<endl; 
} 



//partial specialization 
template<class t> 
class check<t*> 
{ 
int objectsize; 
t* object; 
public: 
check(t*,int); 
t* getelement()const; 
~check(); 
}; 
template<typename t> 
check<t*>::check<t*>(t* ptr,int size) 
{ 
cout<<"\n partial specialization constructor"; 
} 




//derived class 
template< class t> 
class childcheck:public check<t> 
{ 
t chobject; 
public: 
childcheck(t); 
t getobject()const; 
}; 
template<class t> 
childcheck<t>::childcheck(t element):check<t>(element+1) 
{ 
cout<<"derived class constructro"<<endl; 
} 



//and this is the main function 
main() 
{ 
int* ptr; 
int x=2; 
ptr=&x; 
childcheck<int*> object(ptr); 
system("pause"); 
} 

回答

3

check<t*>::check(t*,int); c'tor有两个参数,但是您从派生类初始化列表中调用它作为check<t>(element+1)(使用t == int *,因此部分特化是实例化的)。

+0

是你的权利,非常感谢你 –

0

更一般地说,您面临着专业化的共同问题。

当您编写模板类的专业化时,通常您必须注意它的接口并确保它与您专门设计的模板类的接口相匹配,否则会产生令人讨厌的惊喜。

当然有些情况下,专业化的目标是提供不同的行为,而某些操作不再有意义,但是由于不能再处理任何实例像任何其他模板,必须写的,其界面有所不同专业化的特殊情况......

而你刚刚发现这是没有乐趣;)