默认模板参数部分专业化 [英] Default template parameter partial specialization

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

问题描述

请向我解释为什么下面的代码符合并可以正常工作。
我很困惑。

Please explain to me why the following piece of code complies and works perfectly. I am very confused.

#include<iostream>
template<class A = int, class B=double>
class Base
{};

template<class B>
class Base <int, B>
{
public:
  Base()
  {
     std::cout<<"it works!!!!!\n";
  }
};

int main()
{
  Base<> base; // it prints "it works!!!!!"
  return 0;
}

它不属于模板类Base的广义形式吗? / p>

Shouldn't it fall into the generalized form of the template class Base?

推荐答案

默认参数适用于特殊化-实际上,特殊化必须(可以说)接受基本模板的默认参数。尝试在专业化中指定默认值:

The default argument applies to the specialization -- and, in fact, a specialization must accept (so to speak) the base template's default argument(s). Attempting to specify a default in the specialization:

template<class A = int, class B=double>
class Base
{};

template<class B=char>
// ...

...是错误。

同样,如果我们更改专业化,以使其专业化类型不同于基本模板提供的默认类型,则为 other 类型:

Likewise, if we change the specialization so that its specialization is for a type other than the default provided by the base template:

template<class A = int, class B=double>
class Base
{};

template<class B>
class Base <char, B>

...然后将选择基本模板。

...then the base template will be chosen.

这是怎么回事:首先选择模板参数的类型。在这种情况下(实例化时未指定类型),这两种类型均基于基础模板中指定的默认模板参数。

So, what's happening is this: first the types for the template arguments are chosen. In this case (no type specified at instantiation), both types are based on the default template arguments specified in the base template.

然后(作为一个基本的单独步骤)将其在适合那些参数类型的所有模板上执行重载解析的模拟。与重载解析一样,显式指定的类型通常优先于隐式指定的类型,因此您的专业化(显式指定 int )优先于基本模板(即指定的类型) int 隐式)。

Then (as a basically separate step) it carries out an analog of overload resolution on all templates that fit those argument types. As usual for overload resolution, a type that's specified explicitly is preferred over one that's specified implicitly, so your specialization (which specified int explicitly) is preferred over the base template (which specified int implicitly).

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

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