简体   繁体   English

c11 _Generic添加类型

[英]c11 _Generic adding types

How do you add extra types to c11 _Generic Functions? 如何为c11 _Generic Functions添加额外的类型?

Do you have to #undef/re-#define it?(if so would the following work) or is there a nicer way? 你需要#undef / re- #define吗?(如果有以下工作那样)或者有更好的方法吗?

#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)

I am not sure that I understand your question completely. 我不确定我完全理解你的问题。 You mean that you have a type generic macro that is given by some library and you want to amend it with a new type of your own? 你的意思是你有一个由某个库提供的类型通用宏,你想用你自己的新类型修改它?

What you always could do is to give it another name and use the default case to obtain the provided behavior: 你总是可以做的是给它另一个名字,并使用默认情况来获得提供的行为:

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

Edit : 编辑

This will not work perfectly because you'd have to put the function argument evaluation inside the _Generic . 这将无法正常工作,因为您必须将函数参数评估放在_Generic This means in particular that the type of X has to be compatible with all branches of the nested generic expressions. 这尤其意味着X的类型必须与嵌套通用表达式的所有分支兼容。

It would be easier if the library in question had a macro that would just return the function itself, without the (X) , say to_strGen , and that never would evaluate X . 如果有问题的库有一个只返回函数本身的宏,没有(X) ,比如to_strGento_strGen ,而且永远不会评估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)

If it's your code, you would have to #undef it and re #define it, yes. 如果它是你的代码,你必须#undef它并重新#define它,是的。 There's no way to extend a type-generic expression (AFAIK). 没有办法扩展类型泛型表达式(AFAIK)。

If it's not your code I'd introduce a second expression with the extension like Jens suggested. 如果它不是你的代码,我会引入第二个带有Jens建议扩展名的表达式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM