c語言實現泛型函式

2021-06-04 18:23:42 字數 850 閱讀 5095

liner search:

#include

#include

void * 

lsearch(

void *key, 

void *base, 

int n, 

int elemsize, 

int (*compfunc)(

void *, 

void *))   }

return

null; }

intintcomp(

void *a, 

void *b) 

void

main() ;

int key = 

2; int * result = (

int *)lsearch(&key, arr, 

5, sizeof(

int), intcomp);

if(result == 

null)

printf(

"404 not found");

else

printf(

"found it: %d

\n", *result); }

注意點:

1.c中用 void * 實現泛型, void *指標型別不同於一般的職能型別,比如不能進行指標運算,因為不知道型別,當然這個型別的偏移量也不知道了。

2.intcomp函式不能實現為 int intcomp(int *, int *); 必須為void *。

3.void *的指標運算通常是先轉換成乙個byte的型別(char *),再進行運算。

4.注意string.h中memcpy memcmp strdup函式的用法。

C 泛型約束,泛型函式

class 泛型 sortss new sort 例項化乙個排序類 ss.sortt pr 呼叫排序函式 foreach pression ppr in pr 測試泛型函式 int a 5 console.writeline a a int b 9 console.writeline b b n p...

R語言中泛型函式

r語言1.0 toc whoami function x,usemethod whoami whoami.foo function x print i am a foo whoami.bar function x print i am a bar whoami.default function x ...

使用python實現泛型函式

簡易理解 泛型函式就是你定義函式的時候,能接收萬能型別,在呼叫時,會根據傳入值本身的型別進行區分處理,達到某些效果,好處是 復用率高,減少 冗餘,對物件導向語言中泛型函式概念非常常用.接下來使用到的py庫functools中的singledispatch模組 使用方法 在需要進行泛型的函式上加上裝飾...