How is a template instantiated?

后端 未结 2 810
感情败类
感情败类 2021-02-04 02:51

It\'s an exercise from C++ Primer 5th Edition:

Exercise 16.27: For each labeled statement explain what, if any, instantiations happen. If a tem

2条回答
  •  抹茶落季
    2021-02-04 03:25

    Regarding e and d I will quote the standard 14.7.1

    Unless a function template specialization has been explicitly instantiated or explicitly specialized, the function template specialization is implicitly instantiated when the specialization is referenced in a context that requires a function definition to exist. Unless a call is to a function template explicit specialization or to a member function of an explicitly specialized class template, a default argument for a function template or a member function of a class template is implicitly instantiated when the function is called in a context that requires the value of the default argument.

    Example also from the standard

    template struct Z {
        void f();
        void g();
    };
    
    void h() {
        Z a;     // instantiation of class Z required
        Z* p;   // instantiation of class Z not required
        Z* q; // instantiation of class Z not required
        a.f();        // instantiation of Z::f() required
        p->g();       // instantiation of class Z required, and instantiation of Z::g() required
    }
    

    This means that no instantiation happens in d. While it will be instantiated in e if that function actually needed to call a function from that type ( could be a copy constructor or any other function called inside the function).

提交回复
热议问题