AI智能摘要
泛型编程旨在通过参数化类型实现代码复用,C语言虽不直接支持,但C11标准引入的“泛型选择”(_Generic)机制可在一定程度上实现类型通用处理。该机制根据表达式类型选择对应代码段,常用于宏定义中。示例显示,_Generic可用于识别变量类型并输出对应信息,或调用不同类型对应的函数,提升代码灵活性与通用性。
— 此摘要由AI分析文章内容生成,仅供参考。
![]()
1 泛型编程
泛型编程(Generic Programming)是一种编程范式,旨在通过定义通用的算法和数据结构,使得这些算法和数据结构能够适用于不同的数据类型。它的核心思想是通过参数化类型来实现代码的复用和灵活性。
在泛型编程中,程序员可以编写与类型无关的代码,这些代码可以与任何类型一起工作,而不需要在编写代码时指定具体的类型。这使得代码更加通用、可维护,并减少了重复劳动。
虽然C语言本身不支持泛型编程,但是在C11标准中引入了一种称为“泛型选择”(_Generic)的机制,这使得C语言在一定程度上可以支持泛型编程,但它的功能相对简单,主要用于选择不同的代码段来处理不同类型的表达式。
2 泛型选择
泛型选择需要”_Generic”关键字支持,其是C11标准中的新特性,用于构造泛型选择表达式。通过泛型选择表达式,程序可以根据表达式的类型选择不同的执行代码段,从而实现了类似的泛型编程。以下是泛型选择表达式的通用语法结构:
_Generic(expression, type1: code1, type2: code2, ..., default: default_code)
expression是要根据其类型选择代码的表达式type1,type2, … 是数据类型code1,code2, … 是对应类型的代码块default_code是可选的,作为默认处理路径,当表达式的类型不匹配任何指定类型时执行
3 功能示例
泛型选择表达式不是预处理指令,但是其通常用作为#define宏定义的一部分。泛型选择表达式和switch类似,不过前者用表达式的类型匹配标签,,后者用表达式的值匹配标签。
3.1 类型选择值
#include <stdio.h>
#define print_type(x) _Generic((x), \
int: "int", \
float: "float", \
double: "double", \
char*: "string", \
default: "unknown type")
int main(void)
{
int a = 5;
float b = 3.14F;
double c = 2.718;
char* d = "Hello";
printf("a is of type: %s\n", print_type(a)); // 输出 "a is of type: int"
printf("b is of type: %s\n", print_type(b)); // 输出 "b is of type: float"
printf("c is of type: %s\n", print_type(c)); // 输出 "c is of type: double"
printf("d is of type: %s\n", print_type(d)); // 输出 "d is of type: string"
return 0;
}
程序输出结果为:
a is of type: int
b is of type: float
c is of type: double
d is of type: string
3.2 类型选择函数
#include <stdio.h>
#define print(x) _Generic((x), \
int: print_int, \
double: print_double, \
default: print_unknown)(x)
void print_int(int x) {
printf("Integer: %d\n", x);
}
void print_double(double x) {
printf("Double: %f\n", x);
}
void print_unknown(void *x) {
printf("Unknown type\n");
}
int main() {
int a = 5;
double b = 3.14;
print(a); // Output: Integer: 5
print(b); // Output: Double: 3.14
// This will call print_unknown since 'char' is not defined in _Generic
print('c'); // Output: Unknown type
return 0;
}
卧槽,宏还能这么玩?C党狂喜!
刚试了下,代码贴进去gcc 9.1直接过, 还不快?不过真到项目里写这么一通宏,维护大哥估计会打人 😂
所以和C++模板还是不能比吧,作者能不能写一篇对比?我想看看性能差距