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.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With