Understanding an Implicit Instantiation of Class Template Specialization Example

﹥>﹥吖頭↗ 提交于 2019-12-11 16:46:38

问题


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 templates 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

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