gpt4 book ai didi

c++ - 模板类的虚函数是隐式实例化的吗?

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:23:18 25 4
gpt4 key购买 nike

考虑以下代码。是否保证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);
}

最佳答案

标准部分 14.7.1/11 说

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.

但是,对于典型的 vtable 实现,实例化类的任何构造函数都需要该类存在的 vtable,它必须包含指向特化虚函数定义的指针。所以在实践中,虚函数可能会被实例化。

关于c++ - 模板类的虚函数是隐式实例化的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41174161/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com