Yippie-Ki-Yay
Yippie-Ki-Yay

Reputation: 22854

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;
   }
};

Upvotes: 3

Views: 344

Answers (1)

Johannes Schaub - litb
Johannes Schaub - litb

Reputation: 507393

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.

Upvotes: 7

Related Questions