Decorators In C

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:

#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:

typedef int (* const decorableFnType)(SomeStruct * data);

Again, not super elegant, but handy.