开发者

C++ partial template specialization syntax

开发者 https://www.devze.com 2023-01-30 09:31 出处:网络
for primary template: template<typename A, typename B> class MyClass {... with template specialization, what is the difference between

for primary template:

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

with template specialization, what is the difference between

template<typename A, typename B> cl开发者_运维百科ass MyClass<int, float> {...

and

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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消