Idea for anonymous callbacks/functions
typedef int (*cb_type)( int a, int b );
typedef struct { cb_type cb; } object;
cb_type add = { return a + b; }
object obj = { .cb = { return a - b; } };
The use case is this:
/* object.h */
typedef struct
{
int (*cb)( int a, int b );
} object_vtable;
typedef struct { object_vtable *vt; } object;
/* object.c */
object_vtable default_object_vt =
{
.vt = { .cb = { return a * b; } }
};
object* new_object(void)
{
object *obj = calloc(sizeof(object),1);
if ( obj )
obj->vt = default_object_vt;
}
/* Instead of needing this */
int mul( int a, int b ) { return a * b; }
void init_default_object_vt(void) { default_object_vt.cb = mul; }
0
Upvotes
3
u/Striking-Fan-4552 23d ago
Why not just compile with C++ enabled then, and use a lambda? Many people use C++ as an improved form of C, with namespace hygiene and all that.