c++ - 如何评估预处理器宏中的参数以传递给 sizeof?

标签 c++ c c-preprocessor

我想要一个函数来打印关于结构的成员变量的信息。为了使函数尽可能简单(且无错误),我也不想手动传递类型。这导致我需要能够评估传递到我的宏中的参数:

#ifndef preprocessor_stringify
#define preprocessor_stringify(s) #s
#endif

typedef struct test_s {
    void (*ptr)(void*);
} test;

void doSomething_(char *name, int offset, int size){
    printf("%s %d %d\n", name, offset, size);
}

#define doSomething(name, container) (\
    doSomething_(\
        preprocessor_stringify(name),\
        offsetof(container, name),\
        sizeof(container->name))\
    );

int main(){
    doSomething(ptr, test);
    return 0;
}

这会产生一个编译错误 test.cpp:21:19: 错误:'->' 标记前的预期主表达式 sizeof(容器->名称))\

关于如何解决这个问题的任何想法?理想情况下,我希望该解决方案同时兼容 C 和 C++。

最佳答案

#include <stdio.h>
#include <stddef.h>

#ifndef preprocessor_stringify
#define preprocessor_stringify(s) #s
#endif

typedef struct test_s {
    void (*ptr)(void*);
} test;

void doSomething_(char const *name, int offset, int size){
    printf("%s %d %d\n", name, offset, size);
}

#define doSomething(name, container) (\
    doSomething_(\
        preprocessor_stringify(name),\
        offsetof(container, name),\
        sizeof(((container*)0)->name))\
    );

int main(){
    doSomething(ptr, test);
    return 0;
}

我做了两个改变:

  1. 在 C++ 中,字符串文字是 const char[]

void doSomething_(char const *name, int offset, int size){
  1. 我们想要一个模型对象的大小,所以我们必须制作一个模型:

sizeof(((container*)0)->name))\

其中一条评论提到指针转换很丑。我同意,让我们将它限制在一个我们可以重复使用的宏中。

#define sizeof_member(Class, Member) sizeof ((Class*)0)->Member

#define doSomething(name, container) (\
    doSomething_(\
        preprocessor_stringify(name),\
        offsetof(container, name),\
        sizeof_member(container, name)) \
    );

关于c++ - 如何评估预处理器宏中的参数以传递给 sizeof?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45148437/

相关文章:

c - 如何打印二进制文件的真实内容

c - 如果我不打印 char 数组,函数将返回错误值

C预处理器宏可以生成函数吗?

枚举中的常量在定义中未见

c - 如何将整数数组传递给库函数

c++ - C++ 在线预处理器

c++ - Base64解码错误

c++ - Qt远程数据库与MySql?

c++ - C/C++ : Write and Read Sockets

c++ - boost .asio : can I do async_read and async_write simultaneously from one thread?