Skip to content

Instantly share code, notes, and snippets.

@hashmal
Created February 22, 2013 05:18
Show Gist options
  • Save hashmal/5010909 to your computer and use it in GitHub Desktop.
Save hashmal/5010909 to your computer and use it in GitHub Desktop.
Not necessarily a good idea: "protocols" in plain old C.
#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