C++ template specialization

北城余情 提交于 2019-12-07 13:13:22

问题


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

回答1:


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.



来源:https://stackoverflow.com/questions/4005086/c-template-specialization

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!