"Generic" Data
richw at ada-uts.UUCP
richw at ada-uts.UUCP
Tue Dec 3 02:25:00 AEST 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
More information about the Comp.lang.c
mailing list