Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ template specialization

Hello! Does someone know a way to achieve or emulate the following behaviour? (this code results in compilation-time error).

E.g, I want to add specific template specialization only in derived classes.

struct Base {
   template <typename T> void Method(T a) {
      T b;
   }

   template <> void Method<int>(int a) {
      float c;
   }
};

struct Derived : public Base {
   template <> void Method<float>(float a) {
      float x;
   }
};
like image 479
Yippie-Ki-Yay Avatar asked Mar 10 '26 19:03

Yippie-Ki-Yay


1 Answers

How about overloading

struct Base {
   template <typename T> void Method(T a) {
      T b;
   }

   void Method(int a) {
      float c;
   }
};

struct Derived : public Base {
   using Base::Method;
   void Method(float a) {
      float x;
   }
};

Explicit specializations can't be added like that in your example. In addition, your Base class is ill-formed as you have to define any explicit specialization outside of the class's scope

struct Base {
   template <typename T> void Method(T a) {
      T b;
   }
};

template <> void Base::Method<int>(int a) {
   float c;
}

All explicit specializations need to give the name of the template to be specialized though, or be in the same scope as the template. You can't just write an explicit specialization in a Derived class like that.

like image 164
Johannes Schaub - litb Avatar answered Mar 12 '26 10:03

Johannes Schaub - litb