【问题标题】:Define a struct based on the definition of an existing struct根据现有结构的定义定义结构
【发布时间】:2014-04-28 09:23:31
【问题描述】:

如果我有一个任意结构,有什么方法可以使用宏向该结构添加字段?

例如:

struct foo{
    int a, 
    int b
};

MAGIC(foo, newtype, newname);

评估结果为:

struct foo{
    int a;
    int b;
};

struct magic_foo{
    int a;
    int b;
    newtype newname;

};

我知道这是一个延伸,但我想可能有一些内置宏可以从它的名称中检索结构的定义?

【问题讨论】:

  • 那真的是个魔法 ;-)
  • 这在 C++ 中应该是可能的。
  • 声明包含指向 foo 结构的指针的 magic_foo 结构不是一种解决方案吗?
  • @ChrisMaes 这真的取决于你想做什么海事组织。如果它只是应该是某种容器类型,是的,我会这么说,但你仍然不能使用彼此互换(在 C 中)。
  • @ChrisMaes:一个指针?你想要一个普通的价值......

标签: c macros struct


【解决方案1】:

不是直接的,因为预处理器完全不知道 C 语法(它仅作为标记替换器运行;对先前声明的类型进行内省是不可能的)。

也许这是一条路:

#define STRUCT { \
    int a;             \
    int b;             \
    EXTRA_MEMBER_DECL  \
}

#define EXTRA_MEMBER_DECL /* empty */
struct foo STRUCT;
#define EXTRA_MEMBER_DECL newtype newname;
struct bar STRUCT;

Plan B 可以使用嵌套结构:

struct bar {
    struct foo;
    newtype newmember;
};

【讨论】:

  • 接受“内省是不可能的”
猜你喜欢
  • 1970-01-01
  • 2014-04-05
  • 1970-01-01
  • 1970-01-01
  • 2014-02-06
  • 1970-01-01
  • 2021-02-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多