c11 _通用添加类型 [英] c11 _Generic adding types

查看:239
本文介绍了c11 _通用添加类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何为c11添加额外的类型_Generic Functions?



您是否需要#undef / re-#定义它?(如果是的话,下面的工作)或者有更好的方法?

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


解决方案 div>

我不确定我完全理解你的问题。你的意思是你有一个类型的通用宏,它是由某个库提供的,你想用它自己的新类型修改它?



你总是可以做的是给它另一个名字,并使用默认情况下获得提供的行为:

  #define to_str2(X)_Generic((X ),默认值:to_str(X),int:i_str(X))

/ em>:

这不会完美,因为您必须将函数参数评估放入 _Generic 。这特别意味着 X 的类型必须与嵌套泛型表达式的所有分支兼容。



如果所讨论的库有一个只返回函数本身的宏,而没有(X),比如 to_strGen ,并且永远不会评估 X 。然后你可以这样做:
$ b $ pre $ #define to_str2Gen(X)_Generic((X),默认:to_strGen(X),int:i_str )
#define to_str2(X)to_str2Gen(X)(X)


How do you add extra types to c11 _Generic Functions?

Do you have to #undef/re-#define it?(if so would the following work) or is there a nicer 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)

解决方案

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. This means in particular that the type of X has to be compatible with all branches of the nested generic expressions.

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

这篇关于c11 _通用添加类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆