Bli*_*ver 5 c++ templates template-instantiation
请考虑以下代码.是否保证Derived<int>::foo()会被实例化?foo()是虚拟的,由基类的非虚函数调用.
#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);
}
Run Code Online (Sandbox Code Playgroud)
标准第14.7.1/11节说
如果虚拟成员函数不会被实例化,则实现是否隐式实例化类模板的虚拟成员函数是未指定的.
但是,对于典型的vtable实现,实例化类的任何构造函数都需要存在类的vtable,该类必须包含指向特化的虚函数定义的指针.因此在实践中,虚拟函数可能会被实例化.