Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call a member function of the primary class template from the member function of a specialization

Can I call an unspecialized template method from a specialized one?

This is easy when using inheritance:

class SomeBaseClass {
  virtual void DoWork() { /* Do something */ }
};

class SomeClass : public SomeBaseClass {
  void DoWork() {
    // Do something first
    SomeBaseClass::DoWork();
  }
};

But is a bit different when using templates:

template <class T>
class SomeClass {
  void DoWork();
};

template<class T>
void SomeClass<T>::DoWork() { /* Do something */}

template<>
void SomeClass<int>::DoWork() {
   // Do something first
   DoWork<>(); // Call method from line 8
}

My generic DoWork function has a lot of really good code in it that I'd hate to duplicate. My specialized one just has an extra step that it needs to perform when a specific type is used.

like image 862
Stewart Avatar asked Sep 06 '25 03:09

Stewart


1 Answers

Similar to here, you can do that indirectly:

template <class T>
class SomeClassCommonImpl {
  void DoWork();
};

template<class T>
void SomeClassCommonImpl<T>::DoWork() { /* Do something */}

template <class T>
class SomeClass: public SomeClassCommonImpl<T> {
  // use the default implementation
};

template <>
class SomeClass<int>: public SomeClassCommonImpl<int> {
  void DoWork();
};

template<>
void SomeClass<int>::DoWork() {
   // Do something first
   SomeClassCommonImpl<int>::DoWork<>(); // Call the common method
}
like image 100
EmDroid Avatar answered Sep 07 '25 21:09

EmDroid