我如何在 C 语言中断言两种类型相等?在 C++ 中,我会使用 std::is_same,但搜索 StackOverflow 和其他地方似乎只给出 C++ 和 C# 的结果。在 C 中没有办法做到这一点吗?
请注意,这不是询问变量是否具有特定类型,而是询问两种类型是否相同。
最佳答案
How to assert two types are equal in c?
使用 _Generic
至少可以让您在大多数情况下使用非数组类型。
#define compare_types(T1, T2) _Generic(( (T1){0} ), \
T2: "Same", \
default: "Different" \
)
#include <stdio.h>
#include <stdint.h>
int main() {
// Same range
printf("%ld %lld\n", LONG_MAX, LLONG_MAX);
// Same size
printf("%zu %zu\n", sizeof (long), sizeof (long long));
// Yet different
printf("%s\n", compare_types(long, long long));
// int64_t is a long on my machine
printf("%s\n", compare_types(long, int64_t));
printf("%s\n", compare_types(long long, int64_t));
}
输出
9223372036854775807 9223372036854775807
8 8
Different
Same
Different
改进
此外,更强的比较采用了 A vs B
和 B vs A
测试。这 2 个测试对于 _Generic
的控制表达式很有用,将数组转换为丢失某些类型信息的第一个元素的指针。
#define strong_helper(T1, T2) _Generic(( (T1){0} ), \
T2: 1, \
default: 0 \
)
#define compare_types_strong(T1, T2) (strong_helper(T1,T2) && strong_helper(T2,T1))
printf("%d\n", compare_types_strong(long, int64_t));
printf("%d\n", compare_types_strong(int [3], int *));
输出
1
0
数组和void
还是很麻烦
compare_types_strong(int [3], int [3])
返回 0,因为 _Generic
将控制表达式 int [3]
转换为指向第一个元素类型 (int *
) 的指针。
@PSkocik ,在已删除的评论中指出此方法不适用于 incomplete object type void
.
关于c - 如何断言两种类型在c中是相等的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53840498/