aboutsummaryrefslogtreecommitdiff
path: root/c-templates.c
blob: d9f98461bf90b23b8528efc4b333291a254a29d7 (plain)
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
#include <stdio.h>

// Build using:
//   gcc -E -CC c-templates.c | gcc -E -CC -DDEFINE=\#define -xc - | gcc --std=gnu99 -xc -

#define TEMPLATE_VA_ARGS __VA_ARGS__
#define template(name, ...) /*
*/ DEFINE name(types, ...) __TEMPLATE_##name types f(TEMPLATE_VA_ARGS); }) /*
*/ DEFINE __TEMPLATE_##name(__VA_ARGS__) ({

// template syntax:
//   declare: template(name, ... types) return_t f(... args) { ... body }
//   call:    name((... types), ... args)

template(print_hex, T) void f(T c)       /*
*/{                                      /*
*/    printf("%x\n", c);                 /*
*/}

template(max, T) T f(T a, T b)           /*
*/{                                      /*
*/    return (a > b) ? a : b;            /*
*/}

int main(void)
{
    print_hex((int), 16);
    print_hex((int), '\n');

    printf("%d\n", max((int), 5, 10));
    printf("%f\n", max((float), 362.38098f, 7.4323f));
    printf("%ld\n", max((long), 409343432, 430483249));
    return 0;
}