A subclass as a specialization - that is: adding a method to a specialization

I want to add an extra conversion operator to the template specialization

-can spelcialization inherit all methods from the main template?

template<class T> MyClass { public: operator Foo() { return(getAFoo()); } }; template<> MyClass<Bar> { public: // desire to ADD a method to a specialization yet inherit // all methods from the main template it specializes ??? operator Bar() { return(getABar()); } }; 
+1
source share
2 answers

Specialization of templates is different types and, therefore, does not separate functions.

You can get general functionality by inheriting from a common base class:

 template<class T> struct Base { operator Foo() { return Foo(); } }; template<class T> struct C : Base<T> { // ... }; template<> struct C<Bar> : Base<Bar> { // ... operator Bar() { return Bar(); } }; 
+4
source

You can also enter a template template parameter:

 template<class T, int i=0> MyClass { public: operator Foo() { return(getAFoo()); } }; typedef MyClass<Bar, 1> MyClassBarBase; template<> MyClass<Bar, 0>: public MyClassBarBase { public: // put compatible constructors here // add whatever methods you like } //When the client instantiates MyClass<Bar>, they'll get MyClass<Bar, 0> //because of the default. MyClass<Bar, 0> inherits from MyClass<Bar, 1>, //which is the "vanilla" version the MyClass template for type Bar. You //only need to duplicate the constructor definitions. 

Hop! It starts a lot like metaprogramming patterns! Please, be careful...

0
source

Source: https://habr.com/ru/post/1301767/


All Articles