如何计算预处理器宏中的参数以传递给 sizeof?
How can I evaluate an argument in a preprocessor macro to pass to sizeof?
我想要一个函数来打印出有关结构的成员变量的信息。为了使函数尽可能简单(且无错误(,我也不想手动传入类型。这导致我需要能够评估传递到我的宏中的参数:
#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 %dn", 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: error: expected primary-expression before ‘->’ token
sizeof(container->name))
关于如何解决这个问题的任何想法?理想情况下,我希望解决方案与 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 %dn", 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;
}
我做了两个更改:
- 在 c++ 中,字符串文本是
const char[]
void doSomething_(char const *name, int offset, int size){
- 我们想要一个模型对象的大小,所以我们必须创建一个模型:
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))
);
另一种选择是使用临时对象。
#define doSomething(name, container)
do {
container temp;
doSomething_(
preprocessor_stringify(name),
offsetof(container, name),
sizeof(temp.name)
);
} while(0)
该对象很可能被优化掉了。(可能不适用于复杂C++对象(。
相关文章:
- 如何反转整数参数包
- 使用C++库在Android项目中修改gradle中的cmake参数,用于插入指令的测试
- 如何使用默认参数等选择模板专业化
- 模板参数替换失败,并且未完成隐式转换
- 具有默认模板参数的多态类的模板推导失败
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 函数调用中参数的顺序重要吗
- 如何使我的 sizeof sum 结构与空参数包一起工作
- 为什么数组大小信息可用于"sizeof"运算符和 delete[] 运算符,但在将数组作为参数传递到
- 如何计算预处理器宏中的参数以传递给 sizeof?
- 在可变参数模板中使用 sizeof 运算符跳过递归结束的函数
- 返回取决于sizeof的变量类型..参数包
- 在visual c++中从无序映射继承时,模板参数的sizeof()不正确
- 为什么(void)sizeof(param)不"使用"参数?
- 对作为参数传递的数组使用sizeof
- 如何在带有模板参数的预处理器中使用sizeof
- 作为参数传递的数组sizeof的奇怪行为
- 在类模板特化中使用sizeof模板参数包
- <sizeof(T)> 作为 C++ 中继承的类模板参数