C11 _ Generating add types

How to add additional types to c11 _Generic Functions?

Do you need to # undef / re- # define it? (if it works like that) or is there a better way?

#define to_str(X) _Generic((X), \
    long double: ld_str, \
    double: d_str, \
    float: f_str, \
    )(X)

#undef to_str

#define to_str(X) _Generic((X), \
    long double: ld_str, \
    double: d_str, \
    float: f_str, \
    int: i_str, \
    )(X)

      

+3


source to share


2 answers


I'm not sure I fully understand your question. Do you mean that you have a generic macro type that is provided by some library and you want to modify it with your new type?

What you can always do is give it a different name and use the default case to get the provided behavior:

#define to_str2(X) _Generic((X), default: to_str(X), int: i_str(X))

      

Edit:



It won't work because you will need to put the function argument evaluator inside _Generic

. This means, in particular, that the type X

must be compatible with all branches of nested generic expressions.

It would be easier if the library in question had a macro that would simply return this function, without (X)

, say to_strGen

, and which would never evaluate X

. Then you could do

#define to_str2Gen(X) _Generic((X), default: to_strGen(X), int: i_str)
#define to_str2(X) to_str2Gen(X)(X)

      

+7


source


If this is your code, you should have #undef

it and re #define

, yes. There is no way to extend a type expression (AFAIK).



If this is not your code, I would introduce a second expression with the extension suggested by Jens.

+3


source







All Articles