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

Zac*_*oyd 6 c types assert

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


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

chu*_*ica 5

c - 如何断言两种类型在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));
}
Run Code Online (Sandbox Code Playgroud)

输出

9223372036854775807 9223372036854775807
8 8
Different
Same
Different
Run Code Online (Sandbox Code Playgroud)

改进

此外,更强的比较使用A vs BB vs A测试。这两个测试对于_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 *));
Run Code Online (Sandbox Code Playgroud)

输出

1
0
Run Code Online (Sandbox Code Playgroud)

仍然麻烦数组和 void

compare_types_strong(int [3], int [3])_Generic控制表达式int [3]转换为指向第一个元素类型 ( int *)的指针时返回 0 。

@PSkocik在已删除的评论中指出这种方法不适用于不完整的对象类型 void