如何阅读模板的部分专业化知识? [英] How to read the template partial specialization?
问题描述
假设以下声明:
template <typename T> struct MyTemplate;
以下对部分专业化的定义似乎使用相同的字母T
来表示不同的类型.
The following definition of the partial specialization seems to use the same letter T
to refer to different types.
template <typename T> struct MyTemplate<T*> {};
例如,让我们进行具体的实例化:
For example, let's take a concrete instantiation:
MyTemplate<int *> c;
现在,再次考虑部分专业化的上述定义:
Now, consider again the above definition of the partial specialization:
template <typename T> struct MyTemplate<T*> {};
在此行的第一部分(即template <typename T>
)中,T
是int *
.在该行的第二部分(即MyTemplate<T*>
)中,T
是int
!
In the first part of this line (i.e. template <typename T>
), T
is int *
. In the second part of the line (i.e. MyTemplate<T*>
), T
is int
!
那么,如何理解部分专业化的定义?
So, how is the definition of the partial specialization read?
推荐答案
像这样阅读:
-
主模板说:"
MyTemplate
是具有一个类型参数的类模板":
The primary template says "
MyTemplate
is a class template with one type parameter":
template <typename> struct MyTemplate;
部分专业化说,只要类型为T
,就存在" ...
The partial specialization says, "whenever there exists a type T
"...
template <typename T>
...这样,对于类型T *
"...
... such that a specialization of MyTemplate
is requested for the type T *
"...
struct MyTemplate<T *>
...然后使用此模板的替代定义.
... then use this alternative definition of the template.
您还可以定义显式专业化.例如,可以说当X
类型要求专业化时,请使用以下替代定义:
You could also define explicit specializations. For example, could say "whenever the specialization is requested for type X
, use this alternative definition:
template <> struct MyTemplate<X> { /* ... */ };
请注意,类模板的显式专业化定义类型,而部分模板化的专业化定义模板.
Note that explicit specializations of class templates define types, wheras partial specializations define templates.
以另一种方式查看:部分类模板专门化推断或 pattern-matches ,类模板参数的结构:
To see it another way: A partial class template specialization deduces, or pattern-matches, the structure of the class template arguments:
template <typename T> struct MyTemplate<T *>
// ^^^^^^^^^^^^ ^^^^^
// This is a new template Argument passed to the original class
// template parameter
此新模板的参数名称在结构上与原始类模板的参数的参数匹配.
The parameter names of this new template are matched structurally against the argument of the original class template's parameters.
示例:
-
MyTemplate<void>
:类模板的类型参数为void
,主要模板用于此专业化.
MyTemplate<void>
: The type parameter of the class template isvoid
, and the primary template is used for this specialization.
MyTemplate<int *>
:类型参数为int *
.存在类型T
,即T = int
,这样所请求的类型参数为T *
,因此将模板的部分专业化的定义用于此专业化.
MyTemplate<int *>
: The type parameter is int *
. There exists a type T
, namely T = int
, such that the requested type parameter is T *
, and so the definition of the partial specialization of the template is used for this specialization.
MyTemplate<X>
:参数类型为X
,并且已为该参数类型定义了显式专业化,因此将其使用.
MyTemplate<X>
: The parameter type is X
, and an explicit specialization has been defined for that parameter type, which is therefore used.
这篇关于如何阅读模板的部分专业化知识?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!