C++ partial template specialization syntax
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.
精彩评论