都说泛型是C++的一大特性,我大C语言表示不服
再探类型
C/C++类型由以下各项组成:
- 内存里的’0’、’1’序列
- ‘0’、’1’串占用的内存大小
- 作为操作数时如何解释与输出位模式(如cout、printf、强制类型转换)
- 作为操作数时如何修改位模式(如+、-、*、/)
“泛型”原理
只需要提供内存首地址,类型大小。利用上面提出的前两点,直接操作内存,就能正确实现泛型。而且不需要为每个类型重新生成代码,克服了C++的代码膨胀问题。
热身——swap泛型实现
|
|
测试代码123456789101112int main(){ double a = 2.5; double b = 4.5; int c = 100; int d = 200; printf("a = %f, b = %f\nc = %d, d = %d\n", a, b, c, d); swap(&a, &b, sizeof(double)); swap(&c, &d, sizeof(int)); printf("a = %f, b = %f\nc = %d, d = %d\n", a, b, c, d); return 0;}
终端输出1234a = 2.500000, b = 4.500000c = 100, d = 200a = 4.500000, b = 2.500000c = 200, d = 100
进阶——泛型Stack
头文件
|
|
实现
|
|
用户代码示例
String
123456789101112131415161718192021222324252627282930313233343536void StringFree(void *elem){free(*(char **)elem);}int main(){stack stringStack;StackNew(&stringStack, sizeof(char *), StringFree);char *a;a = strdup("aaa");StackPush(&stringStack, &a);a = strdup("bbb");StackPush(&stringStack, &a);a = strdup("ccc");StackPush(&stringStack, &a);a = strdup("ddd");StackPush(&stringStack, &a);char *getString;StackPop(&stringStack, &getString);printf("%s\n", getString);free(getString);StackPop(&stringStack, &getString);printf("%s\n", getString);free(getString);StackDispose(&stringStack);return 0;}终端输出
12dddcccInt
12345678910111213141516171819202122232425int main(){stack intStack;StackNew(&intStack, sizeof(int), NULL);for (int i = 0; i < 9; i++){StackPush(&intStack, &i);}for (int i = 0; i < 4; i++){int getInt;StackPop(&intStack, &getInt);printf("%d ", getInt);}putchar('\n');StackDispose(&intStack);return 0;}终端输出
18 7 6 5