开发者

templates and inheritance issue!

开发者 https://www.devze.com 2022-12-21 06:46 出处:网络
I have a tempated base class check and publically derived class childcheck. the base class also have a partial specializatin but i inherit the childcheck class from the general templated class( not fr

I have a tempated base class check and publically derived class childcheck. the base class also have a partial specializatin but i inherit the childcheck class from the general templated class( not from the partial specialization of the class check). when i call the constructor of the base class from the initialization list of the derived class, compiler gives error, now if i remove the partial specialization of class check then compiler gives no error, so here is the code

#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");
}


The check<t*>::check(t*,int); c'tor takes two parameters, but you are calling it ascheck<t>(element+1) from the derived class initialization list (with t==int*, so the partial specialization is instanced).


More generally, you are facing a common issues with specializations.

When you write a specialization of a template class, generally you have to pay attention to its interface and make sure it matches the interface of the template class you specialize, otherwise you have those nasty surprises.

Sure there are situations in which the very goal of the specialization is to provide a different behavior and some operations do not make sense any longer, but then you lose the benefit of generic programming since you cannot any longer treat any instance of the template like any other and have to write special cases for the specialization whose interface differ...

And you just found out that it was no fun ;)

0

精彩评论

暂无评论...
验证码 换一张
取 消