如何实现typeof同时兼容位域与直接传入的类型?
通用类型兼容检查宏的需求与测试
问题背景
我可以通过__builtin_types_compatible_p(typeof(x), typeof(y))检查两种类型是否兼容,该方法支持x、y为变量或直接传入类型的场景。但typeof无法直接作用于位域,需使用typeof(+(x))处理,然而typeof(+(int))属于无效语法。
我希望找到一个通用宏,能够同时处理位域、变量及直接传入类型的场景,检查x与y是否可进行类型提升。曾尝试__builtin_choose_expr但未找到可行方案;发现typeof((a)+1)可适配多数情况,但传入数组类型(如int[])会报错,且不确定该方式是否会改变类型导致结果不准确。
测试代码与结果(基于GCC 4.9.2编译)
#define TypesCompatible_1(a, b) __builtin_types_compatible_p(typeof(a), typeof(b)) #define TypesCompatible_2(a, b) __builtin_types_compatible_p(typeof(+(a)), typeof(+(b))) #define TypesCompatible_3(a, b) __builtin_types_compatible_p(typeof((a) + 1), typeof((b) + 1)) int main() { typedef struct { int a : 4; int b : 4; int c : 4; } bitfield; bitfield z; int x, y; int a[5], b[5]; float c; // 1: 标准版本 printf("%d\n", TypesCompatible_1(x, y)); // 输出:1 printf("%d\n", TypesCompatible_1(int, y)); // 输出:1 printf("%d\n", TypesCompatible_1(x, int)); // 输出:1 printf("%d\n", TypesCompatible_1(int, int)); // 输出:1 printf("%d\n", TypesCompatible_1(a, b)); // 输出:1 printf("%d\n", TypesCompatible_1(a, c)); // 输出:0 // printf("%d\n", TypesCompatible_1(z.a, y)); // 报错:‘typeof’ applied to a bit-field // printf("%d\n", TypesCompatible_1(a, z.b)); // 报错:‘typeof’ applied to a bit-field printf("%d\n\n", TypesCompatible_1(int[], int[])); // 输出:1 // 2: 类型提升版本 printf("%d\n", TypesCompatible_2(x, y)); // 输出:1 printf("%d\n", TypesCompatible_2(z.a, y)); // 输出:1 printf("%d\n", TypesCompatible_2(x, z.b)); // 输出:1 printf("%d\n", TypesCompatible_2(z.a, z.b)); // 输出:1 printf("%d\n\n", TypesCompatible_2(z.a, c)); // 输出:0 // printf("%d\n", TypesCompatible_2(int, y)); // 报错:expected expression before ‘)’ token // printf("%d\n", TypesCompatible_2(x, int)); // 报错:expected expression before ‘)’ token // printf("%d\n", TypesCompatible_2(int, int)); // 报错:expected expression before ‘)’ token // printf("%d\n", TypesCompatible_2(a, b)); // 报错:wrong type argument to unary plus // printf("%d\n", TypesCompatible_2(int[], int[])); // 报错:expected expression before ‘)’ token // 3: 修改版本 printf("%d\n", TypesCompatible_3(x, y)); // 输出:1 printf("%d\n", TypesCompatible_3(z.a, y)); // 输出:1 printf("%d\n", TypesCompatible_3(x, z.b)); // 输出:1 printf("%d\n", TypesCompatible_3(z.a, z.b)); // 输出:1 printf("%d\n\n", TypesCompatible_3(z.a, c)); // 输出:0 printf("%d\n", TypesCompatible_3(int, y)); // 输出:1 printf("%d\n", TypesCompatible_3(x, int)); // 输出:1 printf("%d\n", TypesCompatible_3(int, int)); // 输出:1 printf("%d\n", TypesCompatible_3(a, b)); // 输出:1 printf("%d\n\n", TypesCompatible_3(a, c)); // 输出:0 // printf("%d\n", TypesCompatible_3(int[], int[])); // 报错:cast specifies array type return 0; }
内容的提问来源于stack exchange,提问作者Kyle Ponikiewski
相关产品推荐
相关产品推荐

