如何断言两种类型在c中是相等的?

How to assert two types are equal in c?

如何在 C 语言中断言两种类型相等?在 C++ 中,我会使用 std::is_same,但搜索 Whosebug 和其他地方似乎只给出 C++ 和 C# 的结果。在 C 中没有办法做到这一点吗?


注意,这不是在询问变量是否具有特定类型,而是在询问两种类型是否相同。

在 gcc 下,你可以这样做:

#define same_type(a, b) \ 
    static_assert(__builtin_types_compatible_p(typeof(a), typeof(b)), "types do not match")

...

int a, b;
float c;
same_type(a,b);
same_type(a,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 BB 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]) returns 0 as _Generic 将控制表​​达式 int [3] 转换为指向第一个元素类型 (int *) 的指针。

, in a deleted comment, points out this approach will not work for the incomplete object type void.