加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

C模板专业化

发布时间:2020-12-16 09:30:31 所属栏目:百科 来源:网络整理
导读:你好!有人知道实现或模仿以下行为的方法吗? (此代码导致编译时错误). 例如,我想仅在派生类中添加特定的模板特化. struct Base { template typename T void Method(T a) { T b; } template void Methodint(int a) { float c; }};struct Derived : public Ba
你好!有人知道实现或模仿以下行为的方法吗?
(此代码导致编译时错误).

例如,我想仅在派生类中添加特定的模板特化.

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

解决方法

怎么过载

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

无法像示例中那样添加显式特化.此外,您的Base类格式不正确,因为您必须在类的范围之外定义任何显式特化

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

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

所有显式特化都需要将模板的名称赋予特殊性,或者与模板位于同一范围内.你不能像这样在Derived类中编写显式的特化.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读