Created
September 18, 2012 11:58
-
-
Save aprell/3742762 to your computer and use it in GitHub Desktop.
Simple function overloading in 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> | |
/* 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) | |
/* Simple name mangling of function sum based on arity | |
*/ | |
#define __sum_impl2(n, ...) __sum_impl__ ## n(__VA_ARGS__) | |
#define __sum_impl(n, ...) __sum_impl2(n, __VA_ARGS__) | |
#define sum(...) __sum_impl(VA_NARGS(__VA_ARGS__), __VA_ARGS__) | |
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