4

我试图通过创建一个泛型结构在 C 中手动实现多态行为,然后派生的结构(如果你愿意的话)可以通过枚举的值来区分,这样我就可以有一个指向泛型类型的指针,将其取消引用为泛型类型,找出它是什么类型,然后将其取消引用为更具体的类型。

typedef struct{
  enum type structType;
  //... other stuff all the structs share
}generic;

typedef struct{
  generic; //does not work, obviously, nor does (generic){};
  //... other stuff unique to struct type A
}typeA;

我知道我可以在派生结构中声明一个通用结构的命名实例,但这似乎有点混乱,如果有一个整洁的方法,我不希望这样做。

4

2 回答 2

2

你不能总是得到你想要的,但如果你有时尝试一下,好吧,你可能会发现,你得到了你需要的......

有两种基本的方法,有点小技巧:

  1. 使用包含文件(例如):generic.h
  2. 使用 CPP 宏(例如):GENERIC

我在不同时间使用过这两种方法。


这是包含文件 ( generic.h) 的方法:

enum type structType;
int com_fd;
void *com_buf;

而且,这是一个.c使用它的文件:

typedef struct {
#include <generic.h>
} generic;

typedef struct {
#include <generic.h>
    // other stuff unique to struct type A ...
    int typea_value;
} typeA;

这是使用宏的方法:

#define GENERIC \
    enum type structType; \
    int com_fd; \
    void *com_buf

typedef struct {
    GENERIC;
} generic;

typedef struct {
    GENERIC;

    // other stuff unique to struct type A ...
    int typea_value;
} typeA;
于 2020-05-05T00:51:00.407 回答
0

你能声明一个命名结构的匿名实例吗?

不。

然而,代码可以根据行号组成一个名称,以保持其唯一性并带有某种程度的敌意。

现在,当定义代码在文件中移动时,代码不应尝试引用var.member11成员名称的更改。typeA

#define ANON_1(A,B) A##B
#define ANON_2(A,B) ANON_1(A,B)
#define ANON ANON_2(member, __LINE__)

typedef struct{
  int x;
} generic;

typedef struct{
  generic ANON; // name will be something like: member10
  generic ANON; // name will be something like: member11
  int y;
} typeA;

int main() {
  typeA var;
  (void) var;
  return 0;
}

我怀疑虽然要实现 OP 的更高目标,但可能有更好的方法。

于 2020-05-04T22:44:57.657 回答