![]() |
1
PTLin 20 天前
就在 Linux 内核里看到过,这么用的比较多
#define page_folio(p) (_Generic((p), \ const struct page *: (const struct folio *)_compound_head(p), \ struct page *: (struct folio *)_compound_head(p))) |
2
cnbatch OP 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 |
3
cnbatch OP 个人观点:
Linux 源码对于 _Generic 的大部份用法基本上就是常规“重载”式用法,而最值得关注的是使用 _Generic 做拼接,这个实用性不错 NetBSD 的 _Generic 配合 offsetof 非常好,起到了强制类型安全的作用,值得推广 比较遗憾的是,升级到 C11 的老项目并不多 |