Skip to content

Instantly share code, notes, and snippets.

@leok7v
Created August 6, 2024 22:30
Show Gist options
  • Save leok7v/8d118985d3236b0069d419166f4111cf to your computer and use it in GitHub Desktop.
Save leok7v/8d118985d3236b0069d419166f4111cf to your computer and use it in GitHub Desktop.
C99-C23 functors
typedef struct functor_s functor_t;
typedef struct functor_s {
void (*callback)(functor_t* f);
// other fields here
} functor_t;
typedef struct functor_ex_s {
union {
functor_t base;
struct functor_s; // open unnamed struct to push field names up
};
// extra fields here or pointer to extended data:
void* ex_data; // this is what 'that' is for
} functor_ex_t;
// nameless union is not necessary but pushing fields up prevents field names reuse and confusion later
void foo(functor_t* f) {
functor_ex_t* fx = (functor_ex_t*)f;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment