简体   繁体   中英

Is a virtual function of a template class implicitly instantiated?

Consider the following code. Is it guaranteed that Derived<int>::foo() will be instantiated? foo() is virtual and is called by a non-virtual function of the base class.

#include <iostream>

class Base
{
public:
    void bar() { foo(); }
private:
    virtual void foo() = 0;
};

template <typename T> class Derived: public Base
{
public:
    Derived(T t_) : t(t_) {}
private:
    void foo() override { std::cout << t; }
    T t;
};

Derived<int> make_obj()
{
    return Derived<int>(7);
}

Standard section 14.7.1/11 says

It is unspecified whether or not an implementation implicitly instantiates a virtual member function of a class template if the virtual member function would not otherwise be instantiated.

However, for a typical vtable implementation, instantiating any constructor of the class requires a vtable for the class to exist, which must contain a pointer to the specialization's virtual function definition. So in practice the virtual function will probably be instantiated.

Virtual table will always be instantiated for a class hierarchy, however, in your case it will be compiler dependent whether the foo gets actually initialized on a class creation since the class itself is initialized on a stack and never used polymorphocally. The virtual table will be meaningless in your case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM