[英]Why create a struct of function pointers inside a class?
I was digging around in the Vulkan backend for the Skia graphics API, found here , and I don't understand a piece of code.我在 Vulkan 后端挖掘 Skia 图形 API,在此处找到,但我不明白一段代码。
Here's the smallest code example:这是最小的代码示例:
struct VulkanInterface : public SkRefCnt {
public:
VulkanInterface(VulkanGetProc getProc,
VkInstance instance,
VkDevice device,
uint32_t instanceVersion,
uint32_t physicalDeviceVersion,
const VulkanExtensions*);
/**
* The function pointers are in a struct so that we can have a compiler generated assignment
* operator.
*/
struct Functions {
VkPtr<PFN_vkCreateInstance> fCreateInstance;
VkPtr<PFN_vkDestroyInstance> fDestroyInstance;
// a ton more functions here
} fFunctions;
};
Why would you create a struct of function pointers in a class?为什么要在 class 中创建 function 指针的结构?
Why this extra layer of abstraction where you have to add fFunctions->
everywhere?为什么这个额外的抽象层你必须在任何地方添加
fFunctions->
?
I know there's a comment with an explanation and I know what those words mean, but I don't understand the comment as a whole.我知道有一个带有解释的评论,我知道这些词是什么意思,但我不理解整个评论。 I just need it broken down a little more.
我只是需要它再分解一点。 Thanks.
谢谢。
With regular polymorphic inheritance带正则多态 inheritance
struct Base
{
virtual ~Base() = default;
virtual void foo();
// ...
};
struct D1 : Base
{
void foo() override;
// ...
};
struct D2 : Base
{
void foo() override;
// ...
};
You cannot assign to base class without slicing:您不能在没有切片的情况下分配给基础 class:
D1 d1;
Base b = d1;
b.foo(); // call Base::Foo
or treat object with value semantic:或使用值语义处理 object:
D1 d1;
D2 d2;
d2 = d1; // Illegal
you have to use (smart) pointer instead.您必须改用(智能)指针。
In addition, you cannot mix (at runtime) from different virtual functions此外,您不能混合(在运行时)来自不同的虚拟功能
Base base;
base.foo = &D2::foo; // imaginary syntax, Illegal
base.bar = &D1::bar; // imaginary syntax, Illegal
Having those function pointers inside the class allow the above (at the price of bigger object).在 class 内有那些 function 指针允许上述(以更大的对象为代价)。
struct VulkanInterface
{
void (*foo) ();
void (*bar) (VulkanInterface& self);
// ...
};
VulkanInterface makeVulkanInterface1() { return {my_foo, my_bar}; }
VulkanInterface makeVulkanInterface2() { return {my_foo2, my_bar2}; }
VulkanInterface v1 = makeVulkanInterface1();
VulkanInterface v2 = makeVulkanInterface2();
VulkanInterface v = v1;
v = v2;
v.foo = v1.foo;
v.bar(v);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.