C ++ Template Specialization

Hello! Does anyone know a way to achieve or imitate the following behavior? (this code leads to a compile-time error).

For example, I want to add specialized specialization only to 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;
   }
};
+3
source share
1 answer

How about overload

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 cannot be added as in your example. In addition, your base class is poorly formed, since you need to define any explicit specialization outside the scope of the class

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

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

, , , . Derived, .

+7

Source: https://habr.com/ru/post/1771089/


All Articles