我可以制作从其基础继承的模板专业化吗? [英] Can I make a template specialisation that inherits from its base?

查看:35
本文介绍了我可以制作从其基础继承的模板专业化吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

换句话说:是否可以使模板专门化从其基础继承而来,如下所示:

In other words: Is it possible to make a template specialisation that inherits from its base, like this:

template <class T>  
class A{};  
template <>  
class A<int>:public A<>{};  

使A具有A的所有功能? 我是新来的,所以我不知道如何格式化,以防万一代码出现错误.

so that A has all of A's functions? I'm new here, so I dunno how to format, just in case the code comes up incorrectly.

推荐答案

可以,有些技巧.这种模式有时称为模板子类" ,并且在 SeqAn 库中得到了广泛使用.

You can, with a bit of trickery. This pattern is sometimes called "template subclassing" and is used extensively in the SeqAn library.

诀窍是给基类一个附加的模板参数标签,该标签确定类型标识:

The trick is to give the base class an additional template argument tag which determines the type identity:

template <typename T, typename Spec = void>
struct A { … };

// inheritance tag:
struct Derived { };

template <typename T>
struct A<T, Derived> : public A<T, void> { … };

在这里,void表示基(也可以使用专用标签Base,但void可以正常工作),而Derived是空结构,表示派生类.

Here, void denotes the base (you could also use a dedicated tag Base but void works fine) and Derived, an empty struct, denotes the derived class.

现在,您可以按以下方式实例化和使用模板:

Now you can instantiate and use the templates as follows:

A<int> the_base;
A<int, Derived> the_derived;

the_base.do_something();
the_derived.do_something();

对于一个真实的例子,请考虑 String 来自SeqAn的课程:

For a real-world example, consider the String class from SeqAn:

String<Dna> some_dna = "GATTACA";
String<Dna, Packed> more_dna = "GATTACA";

第二种类型是从第一种类型派生的,但是是一种特殊化,可以将其字符尽可能紧密地打包(对于DNA,这意味着在每个字节中放置四个DNA字符).

The second type derived from the first one, but is a specialisation which packs its characters as tightly as possible (for DNA, this means putting four DNA characters in each byte).

这篇关于我可以制作从其基础继承的模板专业化吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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