On 2003-10-13, some one <fr********@yahoo.com> wrote:
I know that C++ lets you overload functions, but how do I overload
functions in C?
You cannot do so arbitrarily, all C solutions require some form of
trickery. Several have been offered to you.
One trickery not yet suggested is to employ a polymorphic interface.
typedef struct polymorph polymorph;
struct polymorph {
void (* const foo)(polymorph *);
};
void foo(polymorph *p) { p->foo(p); }
Now, you get a form of function overloading when you create instances
of polymorph.
struct A {
polymorph interface;
int a;
};
static void A_foo(polymorph *p) {
struct A *me = (void *)p;
printf("a:%d\n", a++);
}
static const polymorph A_interface = { A_foo };
polymorph * create_A(void) {
struct A *i = malloc(sizeof(struct A));
i->interface = A_interface;
i->a = 0;
}
struct B {
polymorph interface;
int b;
};
static void B_foo(polymorph *p) {
struct B *me = (void *)p;
printf("b:%d\n", b--);
}
static const polymorph B_interface = { B_foo };
polymorph * create_B(void) {
struct B *i = malloc(sizeof(struct B));
i->interface = B_interface;
i->b = 0;
}
Now, you can get a form of overloading with the foo() function.
polymorph *a = create_A(); /* a points to a struct A */
polymorph *b = create_B(); /* b points to a struct B */
foo(a); /* will output "a:0" */
foo(b); /* will output "b:0" */
foo(a); /* will output "a:1" */
foo(b); /* will output "b:-1" */
-- James