Template specialization and instantiation

前端 未结 2 1372
轮回少年
轮回少年 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:41

    "Instantiating a template specialization" typically refers to the process of implicit instantiation: substituting specific template arguments into a template definition to obtain an instantiated class, function, etc. Instantiating a template means instantiating a specialization of that template. Usually, the less precise phrasing is used when we're talking about some arbitrary instantiation in the context of language lawyering. You will also find the expression "instantiation of a template", which is synonymous with the instantiated specialization.

    0 讨论(0)
  • 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 <typename T> struct Foo {};
    
    Foo<int> foo;
    

    you have instantiated the template specialization Foo<int>, not the template Foo.

    Update

    Say you have the following class template:

    template <typename T> struct Foo
    {
       static int a;
    };
    
    int getNext()
    {
       static int n = 0;
       return ++n;
    }
    
    template <class T> int Foo<T>::a = getNext();
    

    Explicit template instantiation

    You can create explicit instantiations of Foo<char> and Foo<int> by using:

    template struct Foo<char>;
    template struct Foo<int>;
    

    Even if Foo<char> and Foo<int> 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<double> {};
    

    Use of Foo

    Now, let's see the use of Foo.

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

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

    0 讨论(0)
提交回复
热议问题