类模板特化中模板参数的默认值 [英] Default values of template parameters in the class template specializations
问题描述
请考虑以下代码:
模板< class x1,class x2 = int *>
struct CoreTemplate {};
template< class x1,class x2>
struct CoreTemplate< x1 *,x2 *> {int spec; CoreTemplate(){spec = 1; }};
template< class x>
struct CoreTemplate< x *> {int spec; CoreTemplate(){spec = 3; }};
int main(int argc,char * argv [])
{
CoreTemplate< int *,int *> qq1;
printf(var =%d.\r\\\
,qq1.spec);
CoreTemplate< int *> qq2;
printf(var =%d.\r\\\
,qq2.spec);
}
MSVC编译此代码并在两种情况下选择第二个特殊化。对我来说,这些专业化是相同的。
只是好奇,对此有任何想法吗?
第二个部分特化是合法的,而不是第一个部分。模板参数列表中的第二个模板参数,因此使用 int *
的默认参数,因此它等效于:
template< class x>
struct CoreTemplate< x *,int *> {...};
对于第一个模板参数是指针类型,第二个模板参数 int *
。
这比第一个部分专业化更专业,当第一个模板argument是一个指针类型,第二个模板参数是除 int *
之外的任何指针类型。
在您的计划中, qq1
和 qq2
使用 int *
作为第二个模板参数(显式或使用默认参数),因此都选择第二个实例化。
Consider the following code:
template <class x1, class x2 = int*>
struct CoreTemplate { };
template <class x1, class x2>
struct CoreTemplate<x1*, x2*> { int spec; CoreTemplate() { spec = 1; } };
template <class x>
struct CoreTemplate<x*> { int spec; CoreTemplate() { spec = 3; } };
int main(int argc, char* argv[])
{
CoreTemplate<int*, int*> qq1;
printf("var=%d.\r\n", qq1.spec);
CoreTemplate<int*> qq2;
printf("var=%d.\r\n", qq2.spec);
}
MSVC compiles this code fine and selects the second specialization in both cases. For me these specializations are identical. How legal is the second specialization in the first hand?
Just curious, any thoughts about this?
The second partial specialization is legal, and is not identical to the first.
The second partial specialization doesn't list an argument for the second template parameter in its template argument list, so uses the default argument of int*
, so it is equivalent to:
template <class x>
struct CoreTemplate<x*, int*> { ... };
Which will be selected for any instantiation where the first template argument is a pointer type and the second template argument is int*
.
That is more specialized than the first partial specialization, which will be used when the first template argument is a pointer type and the second template argument is any pointer type except int*
.
In your program both qq1
and qq2
use int*
as the second template argument (either explicitly or using the default argument) so both select the second instantiation.
这篇关于类模板特化中模板参数的默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!