問題描述
請向我解釋為什么下面的代碼能夠完美運(yùn)行.我很困惑.
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;
}
不應(yīng)該屬于模板類Base的泛化形式嗎?
Shouldn't it fall into the generalized form of the template class Base?
推薦答案
默認(rèn)參數(shù)適用于特化——事實(shí)上,特化必須接受(可以這么說)基模板的默認(rèn)參數(shù).嘗試在專業(yè)化中指定默認(rèn)值:
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>
// ...
...是一個(gè)錯(cuò)誤.
同樣,如果我們改變特化,使它的特化是針對一個(gè)類型other而不是基礎(chǔ)模板提供的默認(rèn)值:
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.
所以,發(fā)生的事情是:首先選擇模板參數(shù)的類型.在這種情況下(在實(shí)例化時(shí)沒有指定類型),兩種類型都基于基本模板中指定的默認(rèn)模板參數(shù).
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.
然后(作為一個(gè)基本上獨(dú)立的步驟)它對適合這些參數(shù)類型的所有模板執(zhí)行重載決議的模擬.與通常的重載解析一樣,顯式指定的類型優(yōu)先于隱式指定的類型,因此您的專業(yè)化(顯式指定 int
)優(yōu)先于基本模板(指定 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).
這篇關(guān)于默認(rèn)模板參數(shù)偏特化的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!