Created
August 2, 2023 03:04
-
-
Save refactor/539c567bedfc80e1349fcd93a89a83ce to your computer and use it in GitHub Desktop.
How to overload a function in C, by parameter type & number
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
void scale_circ(Circle_s c[static 1], double scale) { | |
c->radius *= scale; | |
} | |
void scale_rect(Rectangle_s r[static 1], double scale) { | |
r->w *= scale; | |
r->h *= scale; | |
} | |
#define scale(obj, scale) \ | |
_Generic( (obj), \ | |
Rectangle_s* : scale_rect, \ | |
Circle_s* : scale_circ \ | |
) \ | |
((obj), (scale)) | |
/* overload on number of parameter */ | |
void scale_circ_1p(Circle_s c[static 1], double scale); | |
void scale_rect_1p(Rectangle_s r[static 1], double w_scale); | |
void scale_rect_2p(Rectangle_s r[static 1], double w_scale, double h_scale); | |
#define scale2p(obj, ...) \ | |
_Generic( (obj), \ | |
Rectangle_s* : scale_rect_2p \ | |
) \ | |
((obj), __VA_ARGS__) | |
#define scale1p(obj, ...) \ | |
_Generic( (obj), \ | |
Rectangle_s* : scale_rect_1p, \ | |
Circle_s* : scale_circ_1p \ | |
) \ | |
((obj), __VA_ARGS__) | |
#define INVOKE(_1, _2, _3, NAME, ...) NAME | |
#define scale(...) INVOKE(__VA_ARGS__, scale2p, scale1p,)(__VA_ARGS__) | |
/* | |
@see https://www.youtube.com/watch?v=lLv1s7rKeCM&t=2609s | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment