Default values of template parameters in the class

2019-05-11 17:53发布

问题:

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?

回答1:

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.