Home > Enterprise >  (C ) How can I inherit a template class in its specilization class?
(C ) How can I inherit a template class in its specilization class?

Time:10-19

If I have a class like: Vector<T> (a template class), and now I want to specialize it: Vector<int>. How can I inherit from Vector<T>?

My code is:

template<typename T> class Vector&<int>:public Vector <T>

But it gives error:

template parameters not deducible in partial specialization.

How should I deal with it?

I don't actually mean I want to use in Vector. But I want to understand what's wrong in langugae aspect?

Is that means specilization class can't inherit from other template classes?

CodePudding user response:

It looks like you want the specialised Vector<int> to inherit from the general Vector<int>. This is not possible as is, because there can be only one Vector<int>, but with a little trick you can do it. Just add another template parameter, a boolean non-type with a default value. Now for each T, there are two different Vector<T, b>, one for each possible b.

template <class T, bool = true> 
class Vector 
{ void whatever(); };

Regular users just use Vector<float> or Vector<int> without explicitly passing the second argument. But specialisations can pass false if they need to.

template<> 
class Vector<int, true> : public Vector<int, false> 
{ int additional_member; };
  • Related