Relay-Version: version B 2.10 5/3/83; site utzoo.UUCP Posting-Version: Notesfiles $Revision: 1.6.2.16 $; site ada-uts.UUCP Path: utzoo!watmath!clyde!cbosgd!ihnp4!houxm!hjuxa!petsd!peora!codas!akguc!akgua!gatech!seismo!harvard!think!ada-uts!richw From: richw@ada-uts.UUCP Newsgroups: net.lang.c Subject: "Generic" Data Message-ID: <10200027@ada-uts.UUCP> Date: Mon, 2-Dec-85 11:25:00 EST Article-I.D.: ada-uts.10200027 Posted: Mon Dec 2 11:25:00 1985 Date-Received: Fri, 6-Dec-85 07:19:40 EST Lines: 68 Nf-ID: #N:ada-uts:10200027:000:1923 Nf-From: ada-uts!richw Dec 2 11:25:00 1985 Does anybody have any ideas for how one could implement "generic" data types in C? The term generic is borrowed from Ada; "parameterized clusters" in CLU are similar. For instance, I'd like to implement a "package" of routines which deal with lists. These lists can contain elements of any type but share some operations which are independent of the type of the elements. A simple way to do this involves type casting, but loses because type-checking is sacrificed. Specifically, the following illustrates the basic idea: ------------------------- list.h -------------------------- typedef struct List { char *car; struct List *cdr; } List; /** I apologize for using the all-too-common Lispish terminology **/ /** "What do you mean, you don't know what `cdr' means?" **/ /** "Isn't it perfectly obvious???" **/ : extern List *cons(); : ----------------------------------------------------------- ------------------------- list.c -------------------------- #include "list.h" List *cons(car, cdr) char *car; List *cdr; { List *result; result = (List *) malloc(sizeof(List)); result->car = car; result->cdr = cdr; return result; } ----------------------------------------------------------- Users of such a package would need to caste the arguments and results of these functions to and from (char *), e.g.: #include "list.h" : { List *int_list; List *char_list; int_list = cons((char *) 1, cons((char *) 2, NULL)); char_list = cons((char *) 'a', NULL); : } Not only does the user play games with the type-checking, there also is the problem of data-size -- machines whose char pointers are shorter than ints or chars themselves (unlikely, I know, but...) would die given the above. Other ideas which use (ab-use?) the C preprocessor are possible, but are much more involved. -- Rich Wagner