【问题标题】:Is there any difference between empty derived class and using?空派生类和使用之间有什么区别吗?
【发布时间】:2023-01-22 07:53:28
【问题描述】:

我正在编写一个库,其功能在 C 兼容标头中提供,如下所示:

// File: bar.h

typedef struct bar_context_t bar_context_t;

#ifdef __cplusplus
extern "C" {
#endif

  bar_context_t* bar_create();
  void bar_destroy(bar_context_t*);

  int bar_do_stuff(bar_context_t*);

#ifdef __cplusplus
}
#endif

并在 C++ 中实现:

// File: bar.cpp

namespace bar {
  class Context {
    private:
      // ...
    public:
      int do_stuff();
  };
}

问题是如何将 bar::Context 连接到 bar_context_t 以便我可以实现外部 C 函数。

我可以想到两种选择:

选项 A:使用

using bar_context_t = bar::Context;

选项 B:空派生类

struct bar_context_t : public bar::Context {};

哪个选项更好?或者有更好的第三种选择吗?

【问题讨论】:

  • 使用typedef struct bar_context_t bar_context_t;你已经告诉编译器bar_context_t是一个struct,所以你不能真的是using类(因为那会试图“覆盖”你用@创建的类型别名987654331@)。
  • 你可能想多了 - 你可以简单地 reinterpret_cast 并且只要你在使用它之前转换回 bar::Context* 就可以了

标签: c++ inheritance typedef using


【解决方案1】:

两者都不是必需的(我什至认为您的第一个变体不起作用;using 只是 C++ 语法糖,并不引入类型)。

您只需将bar_context_t 声明为指向bar::Context 的指针;就是这样。在 C 中,您将其声明为 void*,因为 C 无论如何都没有类型安全。¹


¹严格来说,C 在“函数指针”和“非函数指针”两种类型之间具有类型安全性。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-12-06
    • 1970-01-01
    • 2011-01-05
    • 2015-02-22
    • 2013-09-13
    • 2017-04-05
    • 2014-09-18
    相关资源
    最近更新 更多