首页 > 解决方案 > 部分模板特化:为什么部分特化列表中的某些变量与主模板不同

问题描述

我正在从 cppreference 学习部分模板专业化,并且我了解部分专业化模板中的参数数量必须与主参数匹配,并且参数列表不能与非专业参数相同。但是,我被变量的命名绊倒了。在下面的代码中:

template<class T1, class T2, int I>
class A {};            // primary template

template<class T, int I>
class A<T, T*, I> {};  // #1: partial specialization where T2 is a pointer to T1

template<class T, class T2, int I>
class A<T*, T2, I> {}; // #2: partial specialization where T1 is a pointer

template<class T>
class A<int, T*, 5> {}; // #3: partial specialization where T1 is int, I is 5,
                        //     and T2 is a pointer

template<class X, class T, int I>
class A<X, T*, I> {};   // #4: partial specialization where T2 is a pointer

我不明白为什么使用 T 和 X 而不是 T1 那样的目的。

标签: c++templates

解决方案


在模板特化中,您为模板参数选择的名称是静默变量。以下所有内容完全相同

template<class T, class U, int N> class A<T, U, N> { /*...*/ };
template<class U, class T, int N> class A<U, T, N> { /*...*/ };
template<class F, class G, int Z> class A<F, G, Z> { /*...*/ };
template<class OnceUpon, class ATime, int ThereWere> class A<OnceUpon, ATime, ThereWere> { /*...*/ };

特别是,选择的名称不必与“原始”模板定义的名称相匹配。


在评论中,你问:

在我的问题 #1 和 #3 的代码中,分别有 2 和 1 个参数列表。比如为什么不包括主模板参数列表中的其他变量?

这就是部分专业化的工作原理。但是让我们备份一下。

这是一个模板类:

template<class T1, class T2>
struct X
{};

这是它的明确专业化:

X<int, int>;

现在,假设我想为X<T1, T2>with定义一个行为T1 == T2,这不仅意味着X<int, int>,还意味着X<double, double>X<float&, float&>X<std::string, std::string>,以及这些显式特化的所有无穷大。

为此,我需要定义一个依赖于一种类型(同时扮演 和 的角色)的部分特T1T2。因此,这种专业化将通过以下方式引入template<class T>:只有一种类型:

template<class T>
struct X<T, T>
{ using type = T; };

如果您使用了两个参数 ( template<class T, class WhatToDoWithThatType>),那么第二个参数有什么用?


推荐阅读