views:

65

answers:

1

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;
   }
};
+7  A: 

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.

Johannes Schaub - litb