gpt4 book ai didi

c++ - 在参数化虚拟中会发生什么?

转载 作者:行者123 更新时间:2023-11-27 23:40:28 25 4
gpt4 key购买 nike

C++ 模板 - 完整指南 中的第 16.4 章参数化虚拟性,由 David Vandevoorde 和 Nicolai M. Josuttis 撰写,他说:

C++ allows us to parameterize directly three kinds of entities through templates: types, constants ("nontypes"), and templates. However, indirectly, it also allows us to parameterize other attributes such as the virtuality of a member function.

该章中说明了以下代码:

#include <iostream>

struct NotVirtual
{};

struct IsVirtual
{
virtual void func() {;}
};

//---------------------//

template<typename T>
struct Base : T
{
void func()
{ std::cout<< "Base::func()" <<std::endl; }
};

template<typename T>
struct Derived : Base<T>
{
void func()
{ std::cout<< "Derived::func()" <<std::endl; }
};

//---------------------//

int main()
{
Base<NotVirtual> *p1 = new Derived<NotVirtual>();
p1->func();
delete p1;

Base<IsVirtual> *p2 = new Derived<IsVirtual>();
p2->func();
delete p2;
}

在线示例:https://rextester.com/OAGC66937

我理解这种技术的用法,但不幸的是,这本书没有提供任何关于这件事是如何发生的进一步细节。可以看出Base其实是一个继承自模板参数T的派生类。

问题:

  1. 参数化虚拟化期间后台发生了什么?
  2. 生成的 v_table 中是否发生了什么?
  3. 模板参数中的virtual是如何传输过来的?

最佳答案

扩展@Quentin 的评论

Once the Base template is specialized for a specific T, everything proceeds as usual through inheritance and virtual overriding.

让我们写出一组等效的非模板类

struct BaseNV : NotVirtual
{
void func() // first definition of func
{ std::cout<< "Base::func()" <<std::endl; }
};

struct DerivedNV : BaseNV
{
void func() // hides BaseNV::func
{ std::cout<< "Derived::func()" <<std::endl; }
};

struct BaseIV : IsVirtual
{
void func() // implicitly virtual, overrides IsVirtual::func
{ std::cout<< "Base::func()" <<std::endl; }
};

struct DerivedIV : BaseIV
{
void func() // implicitly virtual, overrides BaseIV::func (and IsVirtual::func)
{ std::cout<< "Derived::func()" <<std::endl; }
};

int main()
{
BaseNV *p1 = new DerivedNV();
p1->func();
delete p1;

BaseIV *p2 = new DerivedIV();
p2->func();
delete p2;
}

See it live

What happens in the background during parameterized virtuality?

Base<T>继承自 T , 并遵循继承规则

Does something happen in the resulting v_table?

只有普通virtual机制。具体来说,在 NotVirtual如果没有任何虚函数,那么可能不会有任何 vtable。

How does the virtual from the template parameter get transferred over?

按照正常的继承规则

关于c++ - 在参数化虚拟中会发生什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55472947/

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