问题
So this section of the standard gives this example (My questions are inline):
template<class T, class U>
struct Outer {
template<class X, class Y> struct Inner; // Where are X and Y from? Is this defining a struct?
template<class Y> struct Inner<T, Y>; // Is this defining a struct specialization? If so what is Y?
template<class Y> struct Inner<T, Y> { }; // I feel like this is a redefinition of the line above, could it ever not be?
template<class Y> struct Inner<U, Y> { };
};
Admittedly I can't understand the linked section of the standard cause I can't understand what's happening here. I think I'm just getting confused by all the template
s flying around, but If someone could just go line by line and tell me what's happening that would be very helpful.
回答1:
template<class X, class Y> struct Inner; // Where are X and Y from? Is this defining a struct?
This is the declaration of template struct Inner
, X
and Y
is the template parameters.
template<class Y> struct Inner<T, Y>; // Is this defining a struct specialization? If so what is Y?
This is the declaration of a partial specialization, Y
is the template parameter.
template<class Y> struct Inner<T, Y> { }; // I feel like this is a redefinition of the line above, could it ever not be?
This is the definition of the partial specialization, so no redefinition here.
Then use them as:
Outer<foo1, foo2>::Inner<foo3, foo4>* i1;
// the primary template is used, with T=foo1, U=foo2, X=foo3, Y=foo4
// btw the primary template is not defined in this example
Outer<foo1, foo2>::Inner<foo1, foo3> i2;
// the 1st partial specialization is used, with T=foo1, U=foo2, Y=foo3
Outer<foo1, foo2>::Inner<foo2, foo3> i3;
// the 2st partial specialization is used, with T=foo1, U=foo2, Y=foo3
回答2:
Here you go:
template<class T, class U>
struct Outer {
// Forward-declares a struct with two template parameters
template<class X, class Y> struct Inner;
// Forward-declares a partial specialization of Inner
// (Y is its only template parameter)
template<class Y> struct Inner<T, Y>;
// Defines the forward-declared partial specialization
template<class Y> struct Inner<T, Y> { };
// Declares and defines another partial specialization
// (Y is its only template parameter)
template<class Y> struct Inner<U, Y> { };
};
来源:https://stackoverflow.com/questions/47815028/understanding-an-implicit-instantiation-of-class-template-specialization-example