使用宏进行类型检查

Typecheck with Macro

我找到了这段代码并且我明白它的作用(如果 var 是 float 的类型则打印)但我不明白如何:

#include <stdio.h>
#include <stdlib.h>

#define typename(x) _Generic((x), float: "float")

#define isCompatible(x, type) _Generic(x, type: true, default: false)

int main(){
  float var; 
  if(isCompatible(var, float))
    printf("var is of type float!\n");
}

什么是 typename(x)?为什么永远不会被调用? 我也无法理解这个结构:

_Generic(x, type: true, default: false)

有没有办法不将 float 作为参数传递并使其隐式传递?

if(isCompatible(var, float))

我怀疑您想查看 _Generic here - it's a C11 feature (C11 standard (ISO/IEC 9899:2011) s 6.5.1.1 Generic selection (p: 78-79)). See also the accepted answer here.

的文档

本质上,在此示例中,isCompatible 宏调用 _Generic 并且(通过 type: true)returns true if x (第一个参数)与类型 type 兼容,否则 false.

不使用宏 typename,但 returns 文本 float 如果参数与 float 兼容。为什么有一些定义但没有使用的东西你必须问代码的作者。

为什么从未调用 typename 这个问题你应该问代码片段的开发者...

_Generic 关键字是 C11 功能。 这个想法是根据变量的类型生成不同的代码。

C 没有像 Java 这样的 typeof 运算符,因此 Java 看起来像

...
if(typeof(p) == typeof(double)) {
    System.out.println("Got type 1");
} 
if(typeof(p) == typeof(char)) {
     System.out.println("Got type 2");
}
...

可以通过_Generic在C11中通过

实现
#include <stdio.h>

#define PRINT_MY_TYPE_NUMBER(x) _Generic((x), \
    double: printf("Got type 1\n"),\
    char: printf("Got type 2\n") \
)

int main(int c, char** v) {

    double p = 10;

    PRINT_MY_TYPE_NUMBER(p));

}

注意_Generic不支持任意类型,只支持'simple'类型。

如果 variable 具有与 type 兼容的类型,isCompatible(variable, type) 背后的想法是 return true。它取决于 type 被传递,因此它取决于 type 被传递,使 type 隐式传递呈现 isCompatible 无用恕我直言。