Default template parameter partial specialization(默认模板参数偏特化)
问题描述
请向我解释为什么下面的代码能够完美运行.我很困惑.
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).
这篇关于默认模板参数偏特化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:默认模板参数偏特化
基础教程推荐
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- CString 到 char* 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
