C++ partial template specialization syntax

让人想犯罪 __ 提交于 2019-12-20 01:46:11

问题


for primary template:

template<typename A, typename B> class MyClass {...

with template specialization, what is the difference between

template<typename A, typename B> class MyClass<int, float> {...

and

template<> class MyClass<int, float> {...

回答1:


template<typename A, typename B> class MyClass<int, float> {... should be not allowed. Indeed, if you specify the formal parameters A and B, your template should be using them.

The second case is just normal: you say that you are making specialization with no "free" parameters.

An intermediate case could be

template<typename A> class MyClass<A, float> {...

which is again valid: here you are fixing only the 2nd template parameter.

The idea of a partial specialization is following: you make a template with some formal parameters, and use them to express the constraints on the parameters of initial template. The partial specialization's parameters don't need to be the same as the initial template parameters. Example:

template<typename X, typename Y, typename Z> class MyClass<X*, Y(Z&)> {...

would be a valid partial specialization for your case. This can be read as "for arbitrary types X, Y and Z, if MyClass's template parameters match X* and Y(Z&), use this specialization". Compiler should be quite clever in order to match the type pattern.



来源:https://stackoverflow.com/questions/4445593/c-partial-template-specialization-syntax

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