我了解单参数函数的 C11 泛型,如下所示:(来自 here)
#define acos(X) _Generic((X), \
long double complex: cacosl, \
double complex: cacos, \
float complex: cacosf, \
long double: acosl, \
float: acosf, \
default: acos \
)(X)
但是,对于有两个参数的函数来说似乎很痛苦,你需要嵌套调用_Generic
,这真的很难看;摘自同一博客:
#define pow(x, y) _Generic((x), \
long double complex: cpowl, \
double complex: _Generic((y), \
long double complex: cpowl, \
default: cpow), \
float complex: _Generic((y), \
long double complex: cpowl, \
double complex: cpow, \
default: cpowf), \
long double: _Generic((y), \
long double complex: cpowl, \
double complex: cpow, \
float complex: cpowf, \
default: powl), \
default: _Generic((y), \
long double complex: cpowl, \
double complex: cpow, \
float complex: cpowf, \
long double: powl, \
default: pow), \
float: _Generic((y), \
long double complex: cpowl, \
double complex: cpow, \
float complex: cpowf, \
long double: powl, \
float: powf, \
default: pow) \
)(x, y)
有没有办法为多参数函数提供更多人类可读的泛型,例如:
#define plop(a,b) _Generic((a,b), \
(int,long): plopii, \
(double,short int): plopdd)(a,b)
预先感谢您的回复。基本思想是为 _Generic
设置一个宏包装器。
最佳答案
鉴于 _Generic
的控制表达式未被评估,我建议应用一些算术运算来进行适当的类型组合,并打开结果。因此:
#define OP(x, y) _Generic((x) + (y), \
long double complex: LDC_OP(x, y), \
double complex: DC_OP(x, y), \
... )
当然这只适用于某些情况,但您始终可以扩展那些“折叠”类型没有帮助的情况。 (这会让我们处理 array-N-of-char 与 char *
,例如,与链接的 printnl
示例一样,然后如果组合类型是int
,可以返回并检查 char
和 short
。)
关于c - C11 中多参数 C 函数的泛型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17302913/