C11 的 _Generic,现实当中用得多不多?(尤其是公司项目)

113 天前
 cnbatch
逛 reddit 的时候见到这个帖子,自称用 C 语言( C23 标准)练手:

https://www.reddit.com/r/C_Programming/s/liueGRtmXs

讨论当中有人提到 _Generic 或许挺有用,原 OP 认为 nullptr 比 NULL 更好。

C11 标准已经推出十几年了,这个 _Generic 用得多不多?毕竟 C23 引入 nullptr ,就是因为 _Generic 的缘故( N3042 提案)

然后原帖还有人觉得 _Generic 这个名字太糟糕了。我觉得也是,搞出好几个下划线开头的大小写混合关键字,用起来很不方便。

顺便一提,原 OP 的练手项目用的是 xmake 。
我记得 xmake 作者也在 V 站,给你一个大赞,你的项目又帮了一个人。
1790 次点击
所在节点    C
3 条回复
PTLin
113 天前
就在 Linux 内核里看到过,这么用的比较多
#define page_folio(p) (_Generic((p), \
const struct page *: (const struct folio *)_compound_head(p), \
struct page *: (struct folio *)_compound_head(p)))
cnbatch
112 天前
Github 找了下,“练手”项目会用得比较多,大型项目也有在用,只是不算广泛

Linux 内核除了 1 楼提到的,还有类似这种:
https://github.com/torvalds/linux/blob/0e39a731820ad26533eb988cef27ad2506063b5b/include/linux/seqlock.h#L252

#define __seqprop(s, prop) _Generic(*(s), \
seqcount_t: __seqprop_##prop, \
__seqprop_case((s), raw_spinlock, prop), \
__seqprop_case((s), spinlock, prop), \
__seqprop_case((s), rwlock, prop), \
__seqprop_case((s), mutex, prop))

用 _Generic 辅助做拼接


NetBSD 的 indent 用到了:
https://github.com/NetBSD/src/blob/80dbdd9020fb73df509a4d01b0eac6b73d43b29e/usr.bin/indent/args.c#L56

#define get_offset(name, type) \
_Generic((&opt.name), type *: offsetof(struct options, name))

应该是用作类型安全的 offsetof


FreeBSD 自身暂时仍未用到 _Generic ,但引用的第三方工具用到了

https://github.com/freebsd/freebsd-src/blob/d888317796190bec350aea3701b8aed3bfdad4c8/contrib/tzcode/private.h#L870

# define TIME_T_MIN \
_Generic((time_t) 0, \
signed char: SCHAR_MIN, short: SHRT_MIN, \
int: INT_MIN, long: LONG_MIN, long long: LLONG_MIN, \
default: TIME_T_MIN_NO_PADDING)

对应的来源应该是这个
https://github.com/eggert/tz/blob/main/private.h
cnbatch
112 天前
个人观点:

Linux 源码对于 _Generic 的大部份用法基本上就是常规“重载”式用法,而最值得关注的是使用 _Generic 做拼接,这个实用性不错

NetBSD 的 _Generic 配合 offsetof 非常好,起到了强制类型安全的作用,值得推广

比较遗憾的是,升级到 C11 的老项目并不多

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/1151667

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX