C 使用宏进行类型检查

C 使用宏进行类型检查,c,types,macros,c11,C,Types,Macros,C11,我发现了这段代码,我理解它的功能(如果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(

我发现了这段代码,我理解它的功能(如果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");
}
这里有没有一种方法不把float作为参数传递,并使其隐式

if(isCompatible(var, float))

我想您可能想查看
\u Generic
-这是C11特性(C11标准(ISO/IEC 9899:2011)s 6.5.1.1 Generic selection(p:78-79))的文档。另见公认的答案

本质上,在本例中,
isCompatible
宏调用
\u Generic
,并且(通过
type:true
)返回
true
,如果
x
(第一个参数)与type
type
兼容,则返回
false


如果参数与
float
兼容,则不使用宏
typename
,而是返回文本
float
。关于为什么有定义但没有使用的东西,你必须问代码的作者。

为什么从不调用
typename
,这是一个你应该问代码片段开发人员的问题

\u 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");
}
...
可通过C11中的
\u Generic
通过

#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));

}
#包括
#定义打印类型编号(x)通用((x)\
double:printf(“获取类型1\n”)\
char:printf(“获取类型2\n”)\
)
int main(int c,字符**v){
双p=10;
打印“我的”类型“编号(p));
}
注意:
\u Generic
不支持任意类型,只支持“简单”类型


isCompatible(variable,type)
背后的思想是,如果
variable
的类型与
type
兼容,则返回
true
。它取决于被传递的
类型
,因此它取决于被传递的
类型
,使
类型
隐式传递会使
变得不可兼容
无用。

你说的“隐式化”是什么意思?这似乎违背了重点。你应该读到:@interjay我的意思是,如果我总是想知道数据是否是浮点类型,我认为没有必要将浮点作为参数传递,并以另一种方式定义宏。如果你想知道变量是否与类型T兼容,显然你需要告诉编译器T是什么。如果您只需要一个
IsCompatibleWithFloat
宏,该宏只能与
float
一起工作,您可以在其中硬编码
float
,而不是将其作为一个参数。@interjay这正是我想做的,但“硬核心float in there”是什么意思?
#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));

}