Created
February 22, 2013 05:18
-
-
Save hashmal/5010909 to your computer and use it in GitHub Desktop.
Not necessarily a good idea: "protocols" in plain old C.
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
#include <stdio.h> | |
#include <stdlib.h> | |
typedef void *any; | |
#define protocol(n) struct n | |
#define end(_) | |
// DECLARING THE SHOW PROTOCOL /////////////////////////////////////////////// | |
protocol (show) { | |
void (*putLn) (any); | |
}; | |
#define show_putLn(v, prtcl) (prtcl)->putLn (v) | |
end (show); | |
// IMPLEMENTING SHOW ON INT ////////////////////////////////////////////////// | |
void int_putLn (any x) | |
{ | |
printf("%i\n", *(int*)x); | |
} | |
protocol (show) int_show = { | |
int_putLn | |
}; | |
// IMPLEMENTING SHOW ON FLOAT //////////////////////////////////////////////// | |
void float_putLn (any x) | |
{ | |
printf("%f\n", *(float*)x); | |
} | |
protocol (show) float_show = { | |
float_putLn | |
}; | |
// TRYING IT ALL ///////////////////////////////////////////////////////////// | |
int main (int argc, char const *argv[]) | |
{ | |
int a = 42; | |
float b = 3.14; | |
show_putLn (&a, &int_show); | |
show_putLn (&b, &float_show); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment