泛型选择
泛型选择 (Generic Selection) 是 C11 标准引入的一个新特性,它根据表达式的类型来选择不同的值。通过 _Generic 关键字实现。
基本语法
_Generic 的基本语法如下:
c
_Generic(表达式,
类型1: 值1,
类型2: 值2,
default: 默认值
)1
2
3
4
5
2
3
4
5
当编译器评估 _Generic 表达式时,它会:
- 确定括号中表达式的类型
- 在类型列表中查找匹配项
- 如果找到匹配的类型,返回对应的值
- 如果没有找到匹配项,返回
default对应的值
实际示例
c
#include <stdio.h>
#define TYPE_NAME(x) _Generic((x), \
int: "整数", \
double: "双精度浮点数", \
char: "字符", \
default: "未知类型" \
)
int main() {
int i = 42;
double d = 3.14;
char c = 'A';
char* s = "Hello World!";
printf("i 的类型是:%s\n", TYPE_NAME(i));
printf("d 的类型是:%s\n", TYPE_NAME(d));
printf("c 的类型是:%s\n", TYPE_NAME(c));
printf("s 的类型是:%s\n", TYPE_NAME(s));
return 0;
}1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
zsh - generic_type
i 的类型是:整数
d 的类型是:双精度浮点数
c 的类型是:字符
s 的类型是:未知类型
实用场景
创建类型安全的泛型函数。例如:
c
#define MAX(x, y) _Generic((x), \
int: max_int, \
double: max_double, \
float: max_float \
)(x, y)
int max_int(int a, int b) {
return (a > b) ? a : b;
}
double max_double(double a, double b) {
return (a > b) ? a : b;
}
float max_float(float a, float b) {
return (a > b) ? a : b;
}1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
使用时:
c
int a = 3, b = 5;
float c = 2.1, e = 1.2;
double e = 4.3, f = 7.6;
printf("Maximum of %d and %d is %d.\n",a, b, MAX(a, b));
printf("Maximum of %g and %g is %g.\n",c, d, MAX(c, d));
printf("Maximum of %lg and %lg is %lg.\n",e, f, MAX(e, f));1
2
3
4
5
6
7
2
3
4
5
6
7
zsh - generic_max
Maximum of 3 and 5 is 5.
Maximum of 2.1 and 1.2 is 2.1.
Maximum of 4.3 and 7.6 is 7.6.