gpt4 book ai didi

c++ - 类变体类型 : Why a vtable?

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

Variant-like 类型通常通过模拟 Vtables 来实现,参见示例

https://www.youtube.com/watch?v=uii2AfiMA0o

现在,作为替代方案,我们可以简单地使用 switch 语句。

问题:除了如果 variant 应该是一个模板,switch 语句变得困难的事实之外,是否有任何理由更喜欢 vtable 而不是 switch 语句,即如果可能的类型的数量未知?

不同的说法:是否有任何理由执行以下操作而不是在 apply 函数中使用 switch 语句?

#include <iostream>
using namespace std;

enum TypeTag { typeInt = 0, typeDouble = 1, typeChar = 2 };

struct Variant {
TypeTag tag;
union { int i; double d; char c; };
};

template <class F>
void apply (Variant const & v, F f) {
struct Helper {
static void callInt (Variant const & v, F f) { f.callInt (v.i); }
static void callDouble (Variant const & v, F f) { f.callDouble (v.d); }
static void callChar (Variant const & v, F f) { f.callChar (v.c); }
};
using hp = void (*) (Variant const & v, F f);
static constexpr hp vtable [3] = {
&Helper::callInt, &Helper::callDouble, &Helper::callChar
};
(vtable [v.tag]) (v, f);
}


int main() {
struct {
void callInt (int) const { std::cout << "Int\n"; }
void callDouble (double) const { std::cout << "Double\n"; }
void callChar (char) const { std::cout << "Char\n"; }
} multifunction;
Variant v;
v.tag = typeDouble; v.d = 2.0;
apply (v, multifunction);
return 0;
}

最佳答案

Differently stated: Is there any reason for doing the following rather than using a switch statement in the apply function?

我看不出这两种方法在 apply 函数的程序集(大体上)看起来会有什么不同。在这两种情况下,您基本上都将拥有一个基于 v.tag 值的跳转表,并立即调用相应的函数然后返回。

我假设 switch 版本对编译器来说会稍微透明一些,因为它不会涉及通过函数指针的间接寻址。因此,出于这个原因,Switch 版本最终可能会更快。

我认为支持 vtable 方法的主要原因是,例如,如果您想基于 C++11 可变参数模板制作模板变体类,则实现 vtable 方法可能更容易,因为我认为很难使用模板合成 switch 语句。 (至少,在稍微考虑一下之后,我不知道我会怎么做。)

关于c++ - 类变体类型 : Why a vtable?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32211368/

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