繁体   English   中英

为什么要在 class 中创建 function 指针结构?

[英]Why create a struct of function pointers inside a class?

我在 Vulkan 后端挖掘 Skia 图形 API,在此处找到,但我不明白一段代码。

这是最小的代码示例:

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;
};

为什么要在 class 中创建 function 指针的结构?

为什么这个额外的抽象层你必须在任何地方添加fFunctions->

我知道有一个带有解释的评论,我知道这些词是什么意思,但我不理解整个评论。 我只是需要它再分解一点。 谢谢。

带正则多态 inheritance

struct Base
{
    virtual ~Base() = default;
    virtual void foo();
    // ...
};

struct D1 : Base
{
    void foo() override;
    // ...
};

struct D2 : Base
{
    void foo() override;
    // ...
};

您不能在没有切片的情况下分配给基础 class:

D1 d1;
Base b = d1;
b.foo(); // call Base::Foo

或使用值语义处理 object:

D1 d1;
D2 d2;
d2 = d1; // Illegal

您必须改用(智能)指针。

此外,您不能混合(在运行时)来自不同的虚拟功能

Base base;
base.foo = &D2::foo; // imaginary syntax, Illegal
base.bar = &D1::bar; // imaginary syntax, Illegal

在 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM