- 论坛徽章:
- 24
|
本帖最后由 zhujiang73 于 2011-04-24 12:10 编辑
C缺少一个重要的特性,就是template和泛型编程......
holyfire 发表于 2011-04-23 23:41 ![]()
void* 就是 C 的泛型。 {:3_189:}- #include <stdio.h>
- #include <stdlib.h>
- typedef struct _GTBase
- {
- void (*add)(void *pthis, void *p);
- } GTBase;
- typedef struct _GTInt
- {
- GTBase base;
- int data;
- } GTInt;
- typedef struct _GTDouble
- {
- GTBase base;
- double data;
- } GTDouble;
- void add_int(void *pthis, void *p)
- {
- GTInt *p_gthis = (GTInt*)pthis;
- GTInt *p_gp = (GTInt*)p;
- p_gthis->data = p_gthis->data + p_gp->data;
- }
- void add_double(void *pthis, void *p)
- {
- GTDouble *p_gthis = (GTDouble*)pthis;
- GTDouble *p_gp = (GTDouble*)p;
- p_gthis->data = p_gthis->data + p_gp->data;
- }
- void gtint_init(GTInt *p_gthis)
- {
- GTBase *p_base = (GTBase*)p_gthis;
- p_base->add = add_int;
- }
- void gtdouble_init(GTDouble *p_gthis)
- {
- GTBase *p_base = (GTBase*)p_gthis;
- p_base->add = add_double;
- }
- void add(void* pina, void* pinb, void* pout)
- {
- GTBase *pb_out = (GTBase*)pout;
- pb_out->add(pout, pina);
- pb_out->add(pout, pinb);
- }
- int main()
- {
- GTInt ia,ib,ic;
- gtint_init(&ia);
- gtint_init(&ib);
- gtint_init(&ic);
- ia.data = 2;
- ib.data = 3;
- ic.data = 0;
- add((void*)&ia, (void*)&ib, (void*)&ic);
- printf("ia=%d, ib=%d, ia+ib=%d\n\n", ia.data, ib.data, ic.data);
- GTDouble da,db,dc;
- gtdouble_init(&da);
- gtdouble_init(&db);
- gtdouble_init(&dc);
- da.data = 1.1;
- db.data = 2.5;
- dc.data = 0.0;
- add((void*)&da, (void*)&db, (void*)&dc);
- printf("da=%f, db=%f, da+db=%f\n\n", da.data, db.data, dc.data);
- return 0;
- }
复制代码 |
|