It can be done with X_MACRO
's.
Do something like this:
#define X_BG_MEMBERS
X(char, MrChar)
X(int, MrInt)
X(long, MrLong)
typedef struct {
#define X(type, member) type member;
X_BG_MEMBERS
#undef X
} Bg_Typedef;
Bg_Typedef FooStr;
Define a function which will count the members. Can also just be a variable, but make the variable static const
so that it is not overwritten
static int
bg_members_count() {
#define X(_, __) +1
static int COUNT = 0
X_BG_MEMBERS;
#undef X
return COUNT;
}
Now you can do something like this in main:
#include <stdio.h>
...
int main() {
printf("The number of members defined in Bg_Typedef is %d
", bg_members_count());
}
You should get something like:
The number of members defined in Bg_Typedef is 3
You might also just want a constant, so you can do the following
#define X(_, __) +1
static const int COUNT = X_BG_MEMBERS;
#undef X
Alternative Pattern
In order to avoid having lots of #define X...
followed by #undef X
, it may be beneficial to do something like this instead:
#define X_BG_MEMBERS(X)
X(char, MrChar)
X(int, MrInt)
X(long, MrLong)
#define BG_STRUCT_FIELD(type, field) type field;
#define BG_COUNT_MEMBER(_, __) +1
typedef struct {
X_BG_MEMBERS(BG_STRUCT_FIELD)
} Bg_Typedefarguably;
static int
bg_members_count() {
static int COUNT = X_BG_MEMBERS(BG_COUNT_MEMBER);
return COUNT;
}
// OR constant
// static const int COUNT = X_BG_MEMBERS(BG_COUNT_MEMBER);
It works the same as the above, but should be noticeably more readable. See ref.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…