Default values of template parameters in the class template specializations

最后都变了- 提交于 2019-12-07 17:31:59

问题


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.



来源:https://stackoverflow.com/questions/11148845/default-values-of-template-parameters-in-the-class-template-specializations

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!