Default template parameter values ​​in specialized class templates

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 perfectly and chooses a second specialization in both cases. For me, these specializations are identical. How legitimate is the second specialization in the first place?

Just curious, any thoughts on this?

+3
c ++ visual-c ++ templates template-specialization
source share
1 answer

The second partial specialization is legal and not identical to the first.

The second partial specialization does not list the argument for the second template parameter in the template argument list, therefore it uses the default argument int* , therefore it is equivalent:

 template <class x> struct CoreTemplate<x*, int*> { ... }; 

which will be selected for any instance where the first argument of the template is a pointer type and the second argument of the template is int* .

This 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 other than int* .

In your program, both qq1 and qq2 use int* as the second argument to the template (either explicitly or using the default argument), so both select the second instance.

+4
source share

All Articles