問題描述
請向我解釋為什么下面的代碼能夠完美運行.我很困惑.
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).
這篇關于默認模板參數偏特化的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!