Template specialization and instantiation

前端 未结 2 1378
轮回少年
轮回少年 2021-01-12 03:49

These concepts is a bit unclear to me. Well, template instantiation\'s defined pretty well by N4296::14.7 [temp.spec]:

The act of instant

2条回答
  •  青春惊慌失措
    2021-01-12 04:50

    Question:

    What's the definition of the instantiation of the template specialization, not just the instantiation of a template?

    My understanding:

    There is no such thing as instantiation of a template. You always instantiate a template specialization.

    If you have:

    template  struct Foo {};
    
    Foo foo;
    

    you have instantiated the template specialization Foo, not the template Foo.

    Update

    Say you have the following class template:

    template  struct Foo
    {
       static int a;
    };
    
    int getNext()
    {
       static int n = 0;
       return ++n;
    }
    
    template  int Foo::a = getNext();
    

    Explicit template instantiation

    You can create explicit instantiations of Foo and Foo by using:

    template struct Foo;
    template struct Foo;
    

    Even if Foo and Foo are not used anywhere else in your code, the class template is instantiated for char and int.

    Explicit template specialization

    You can create explicit specializations of the class template by using:

    template <> Foo {};
    

    Use of Foo

    Now, let's see the use of Foo.

    Foo f1;    // An explicit instantiation has already been created.
                    // No need for any further code creation.
    
    Foo f2; // An explicit specialization has already been created.
                    // No need for any further code creation.
    
    Foo f3;   // There is no explicit instantiation or explicit specialization
                    // Code needs to be created for Foo
    
               
    

    The third case, Foo f3; triggers creation of the template specialization Foo. I interpret the phrase "class template specialization is implicitly instantiated" to mean "creation of Foo from the class template.".

提交回复
热议问题