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).
这篇关于默认模板参数偏特化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:默认模板参数偏特化
基础教程推荐
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 这个宏可以转换成函数吗? 2022-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 常量变量在标题中不起作用 2021-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
