Skip to content

Instantly share code, notes, and snippets.

@aprell
Created September 18, 2012 12:08
Show Gist options
  • Save aprell/3742783 to your computer and use it in GitHub Desktop.
Save aprell/3742783 to your computer and use it in GitHub Desktop.
Simple function overloading in C (extended)
#ifndef OVERLOAD__FN__H
#define OVERLOAD__FN__H
#ifndef VA_NARGS
/* Count variadic macro arguments (1-10 arguments, extend as needed)
*/
#define VA_NARGS_IMPL(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10, N, ...) N
#define VA_NARGS(...) VA_NARGS_IMPL(__VA_ARGS__, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1)
#endif
/* Simple name mangling of function _FN_ based on arity
*/
#define ___FN__impl2(n, ...) ___FN__impl__ ## n(__VA_ARGS__)
#define ___FN__impl(n, ...) ___FN__impl2(n, __VA_ARGS__)
#define _FN_(...) ___FN__impl(VA_NARGS(__VA_ARGS__), __VA_ARGS__)
#endif // OVERLOAD__FN__H
#!/bin/bash
usage="Usage: $0 FUNCTION..."
if [ $# -lt 1 ]; then
echo $usage
exit 0
fi
for fn in "$@"; do
echo "Generating overload_$fn.h"
sed s/_FN_/$fn/g overload.h.in > overload_$fn.h
done
#include <stdio.h>
#include "overload_sum.h"
int sum(int a, int b)
{
return a + b;
}
int sum(int a, int b, int c)
{
return a + b + c;
}
double sum(double a, double b, double c, double d)
{
return a + b + c + d;
}
int main(void)
{
printf("%d\n", sum(1, 2));
printf("%d\n", sum(1, 2, 3));
printf("%g\n", sum(1, 2, 3, 4));
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment