Skip to content

Instantly share code, notes, and snippets.

@JackyYin
Last active November 10, 2022 03:20
Show Gist options
  • Save JackyYin/9f08c0cf71b57258090a45aa3ae5d846 to your computer and use it in GitHub Desktop.
Save JackyYin/9f08c0cf71b57258090a45aa3ae5d846 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#define ___CONCAT(a,b) a ## b
#define ___APPLY(fn,n) ___CONCAT(fn, n)
#define _TYPE_VAL_MAP(t, v) t v
#define _VAL_MAP(t, v) v
#define _MAP0(args...)
#define _MAP1(m, t, v, args...) m(t, v)
#define _MAP2(m, t, v, args...) m(t, v), _MAP1(m, args)
#define _MAP3(m, t, v, args...) m(t, v), _MAP2(m, args)
#define _MAP4(m, t, v, args...) m(t, v), _MAP3(m, args)
#define _MAP5(m, t, v, args...) m(t, v), _MAP4(m, args)
#define _MAP6(m, t, v, args...) m(t, v), _MAP5(m, args)
#define _f(x, name, ret, args...) \
ret name(_MAP##x(_TYPE_VAL_MAP, args)); \
static ret ____##name(_MAP##x(_TYPE_VAL_MAP, args)); \
ret name(_MAP##x(_TYPE_VAL_MAP, args)) { return ____##name(_MAP##x(_VAL_MAP, args)); }; \
static ret ____##name(_MAP##x(_TYPE_VAL_MAP, args))
#define DECLARE_FUNC_0(name, ret, args...) _f(0, name, ret, args)
#define DECLARE_FUNC_1(name, ret, args...) _f(1, name, ret, args)
#define DECLARE_FUNC_2(name, ret, args...) _f(2, name, ret, args)
#define DECLARE_FUNC_3(name, ret, args...) _f(3, name, ret, args)
#define DECLARE_FUNC_4(name, ret, args...) _f(4, name, ret, args)
#define DECLARE_FUNC_5(name, ret, args...) _f(5, name, ret, args)
#define DECLARE_FUNC_6(name, ret, args...) _f(6, name, ret, args)
#define ___nth(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, N, ...) N
#define ___narg(...) ___nth(_, ##__VA_ARGS__, 6, 6, 5, 5, 4, 4, 3, 3, 2, 2, 1, 1, 0)
#define DECLARE_FUNC(name, ret, args...) \
___APPLY(DECLARE_FUNC_, ___narg(args))(name, ret, args)
DECLARE_FUNC(mul, void, int, a, int, b) {
printf("%d\n", a * b);
}
DECLARE_FUNC(cube, void, int, x) {
printf("%d\n", x*x*x);
}
DECLARE_FUNC(add6, void, int, a, int, b, int, c, int, d, int, e, int, f) {
printf("%d\n", a+b+c+d+e+f);
}
int main() {
cube(2);
cube(3);
cube(4);
mul(2, 1);
mul(2, 2);
mul(2, 4);
mul(2, 8);
add6(1,2,3,4,5,6);
add6(7,8,9,10,11,12);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment