默认模板参数偏特化

请向我解释为什么下面的代码能够完美运行.我很困惑.

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

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

不应该属于模板类Base的泛化形式吗?

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).

相关文章