Turns out you can also do decorators in C, this came in handy for something else I had to work on recently. It’s not quite as nice, because functions aren’t first-class, but handy nonetheless.
Here’s what that looks like:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
#include <stdio.h> typedef int (* const decorableFnType)(int paramOne, int paramTwo); int functionOne(int paramOne, int paramTwo) { printf("functionOne: %d, %dn", paramOne, paramTwo); return 0; } int functionTwo(int paramOne, int paramTwo) { printf("functionTwo: %d, %dn", paramOne, paramTwo); return 0; } int functionThree(int paramOne, int paramTwo) { printf("functionThree: %d, %dn", paramOne, paramTwo); return 0; } int decorator(int paramOne, int paramTwo, decorableFnType originalFn) { printf("decorator precondition!n"); originalFn(paramOne, paramTwo); return 0; } int main(int argc, char **argv) { printf("hello, C decorators!n"); functionOne(1, 2); decorator(1, 2, functionOne); decorator(1, 2, functionTwo); decorator(1, 2, functionThree); return 0; } |
The output of which is:
vilimpoc@funky:~$ ./c-decorators
hello, C decorators!
functionOne: 1, 2
decorator precondition!
functionOne: 1, 2
decorator precondition!
functionTwo: 1, 2
decorator precondition!
functionThree: 1, 2
vilimpoc@funky:~$
This might be a bit simplistic, in reality, you’d probably want to decorate a function with a signature like the following, so that you can just change the structure and not bother w/a bajillion function declarations:
1 |
typedef int (* const decorableFnType)(SomeStruct * data); |
Again, not super elegant, but handy.