C ++模板专业化 [英] C++ template specialization

查看:124
本文介绍了C ++模板专业化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好!有人知道如何实现或模拟以下行为?
(此代码导致编译时错误)。

Hello! Does someone know a way to achieve or emulate the following behaviour? (this code results in compilation-time error).

例如,我只想在派生类中添加特定的模板专用化。

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类是不成形的,因为你必须在类的范围之外定义任何显式的专门化。

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

所有显式特化都需要指定模板的名称,或与模板在相同的范围。你不能只是在类似这样的Derived类中写一个明确的专门化。

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.

这篇关于C ++模板专业化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆