Search code examples
cgeneric-programmingc11

_Generic and functions with several parameters


I was reading this C11's _Generic example on Wikipedia:

#define cbrt(X) _Generic((X), long double: cbrtl, \
                          default: cbrt, \
                          float: cbrtf)(X)

It seems pretty clear how to use it for functions with only one parameter, but I can't see a way to write functions with two (or more) generic parameters with this system. How could it be possible?

I would have tried some things if some compiler supported this feature but I could not find one either, so I was unable to find any idea on how to do that.


Solution

  • Obviously there is no "generic" rule for this, it really depends on the use case. But one typical use case would be to use the standard promotions to determine a common "supertype"

    #define pow(X, Y) _Generic((X)+(Y), long double: powl, \
                              default: pow,                \
                              float: powf)((X), (Y))
    

    If X and Y wouldn't agree in type when calling this macro, the narrow one would automatically be promoted to the wider one.