C 能否声明命名结构的匿名实例?

C 能否声明命名结构的匿名实例?,c,anonymous-struct,C,Anonymous Struct,我试图在C中手动实现多态行为,方法是创建泛型结构,然后创建派生结构(如果愿意的话),通过枚举的值来区分派生结构,这样我就可以有一个指向泛型类型的指针,将其作为泛型类型取消引用,找出它是什么类型,然后将其作为更具体的类型取消引用 typedef struct{ enum type structType; //... other stuff all the structs share }generic; typedef struct{ generic; //does not work,

我试图在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;

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

能否声明命名结构的匿名实例

没有

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

现在,代码不应尝试引用
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的更高目标,一个更好的方法是可能的

你不可能总是得到你想要的,但是如果你有时尝试,那么,你可能会发现,你得到了你需要的

有两种基本的方法,稍微有点诡计:

  • 使用包含文件(例如):
    generic.h
  • 使用CPP宏(例如):
    GENERIC
  • 我在不同的时候都用过这两种方法


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

    下面是一个使用它的
    .c
    文件:

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

    人们通常使用联合来实现这种多态性。为什么要使用匿名结构?
    这似乎有点混乱
    命名结构的成员是混乱的?您的代码实际上与
    MSVC
    clang cl
    一起工作,但有以下几点:警告:匿名结构是Microsoft的扩展[-Wmicrosoft anon tag]!如果通过
    -fms extensions启用了Microsoft扩展,则gcc也允许此操作参见gcc文档:
    
    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;