我听说 C11 添加了泛型。我用谷歌搜索了一下,看了一些文章,了解到有一个新关键字 ( _Generic
) 等等。但我似乎无法掌握这一切。
它是类似于 C# 中的泛型还是 C++ 中的模板?谁能给我简要解释泛型的 C11 定义、语法和简单的示例用法示例?
最佳答案
The best example I have seen启发了以下(可运行的)示例,它解锁了破解内省(introspection)的各种怪异可能性......
#include <stdio.h>
#include <stddef.h>
#include <stdint.h>
#define typename(x) _Generic((x), /* Get the name of a type */ \
\
_Bool: "_Bool", unsigned char: "unsigned char", \
char: "char", signed char: "signed char", \
short int: "short int", unsigned short int: "unsigned short int", \
int: "int", unsigned int: "unsigned int", \
long int: "long int", unsigned long int: "unsigned long int", \
long long int: "long long int", unsigned long long int: "unsigned long long int", \
float: "float", double: "double", \
long double: "long double", char *: "pointer to char", \
void *: "pointer to void", int *: "pointer to int", \
default: "other")
#define fmt "%20s is '%s'\n"
int main() {
size_t s; ptrdiff_t p; intmax_t i; int ai[3] = {0}; return printf( fmt fmt fmt fmt fmt fmt fmt fmt,
"size_t", typename(s), "ptrdiff_t", typename(p),
"intmax_t", typename(i), "character constant", typename('0'),
"0x7FFFFFFF", typename(0x7FFFFFFF), "0xFFFFFFFF", typename(0xFFFFFFFF),
"0x7FFFFFFFU", typename(0x7FFFFFFFU), "array of int", typename(ai));
}
╔═══════════════╗ ═════════════════╣ Amazeballs... ╠═════════════════════════════════════ ╚═══════════════╝ size_t is 'unsigned long int' ptrdiff_t is 'long int' intmax_t is 'long int' character constant is 'int' 0x7FFFFFFF is 'int' 0xFFFFFFFF is 'unsigned int' 0x7FFFFFFFU is 'unsigned int' array of int is 'other'
关于c - C11 中 _Generic 的语法和示例用法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9804371/