Home > OS >  How can I use a decorated name with _Generic?
How can I use a decorated name with _Generic?

Time:02-10

I'm writing a library which lets the user decorate the function names like this:

#ifndef DECORATE // Define this before including if you want to change the names.
#define DECORATE(name) lib_##name
#endif

I now what to use _Generic to create a generic function foo like this:

#define DECORATE(foo)(x)            \
    _Generic((x),                   \
             int:   DECORATE(fooi), \
             float: DECORATE(foof)  \
    )(x)

This of course gives me an error, because I can't define the DECORATE macro twice. Is there a way to decorate the name of the generic function or is this impossible?

CodePudding user response:

You need to give your macros two different names so one can use the other. Also, in the case of the one using _Generic, both parameters need to be in one set of parenthesis separated by spaces.

#ifndef DECORATEX 
#define DECORATEX(name) lib_##name
#endif

#define DECORATE(foo,x)            \
    _Generic((x),                   \
             int:   DECORATEX(foo##i), \
             float: DECORATEX(foo##f)  \
    )(x)


void lib_abci(int x)
{
    printf("in abci, x=%d\n", x);
}

void lib_abcf(float x)
{
    printf("in abcf, x=%f\n", x);
}

int main()
{
    int a=3;
    float b=4.5;
    DECORATE(abc,a);
    DECORATE(abc,b);
    return 0;
}

Output:

in abci, x=3
in abcf, x=4.500000
  • Related