c++ - C 或 C++ 中没有 ifdef 的结构
问题描述
有一些 C 项目的结构充满了 ifdef(例如 WolfSSL https://github.com/wolfSSL/wolfssl/blob/bb70fee1ecff8945af8179f48e90d78ea7007c66/wolfssl/internal.h#L2792)
struct {
int filed_1;
int field_2;
#ifdef SETTING_A
int filed_b;
#endif
#ifdef SETTING_B
int field_b;
#endif
}
原因是减少未使用选项的结构大小。有很多ifdef!到处!
有没有 C++ 方法来摆脱那些 ifdef,保留编译器优化未使用字段的能力?也许使用模板、使用或 CRTP 继承?
解决方案
你可以用 C++20和[[no_unique_address]]
一些诡计来做到这一点。但是,这并不能保证会导致较小的类型,因此我仍然建议您使用#define
s
template<typename>
struct Empty {};
template<typename T, bool enable, typename uniquer>
using MaybeEmpty = std::conditional_t<enable, T, Empty<uniquer>>;
struct foo {
int filed_1;
int field_2;
[[no_unique_address]] MaybeEmpty<int, settingA, struct filed_b_uniquer> filed_b;
[[no_unique_address]] MaybeEmpty<int, settingB, struct field_b_uniquer> field_b;
};
在 C++20 之前,必须使用基类来完成
struct with_filed_b {
int filed_b;
};
struct with_field_b {
int field_b;
};
struct foo : MaybeEmpty<with_filed_b, settingA, struct filed_b_uniquer>, MaybeEmpty<with_field_b , settingB, struct field_b_uniquer> {
int filed_1;
int field_2;
};
推荐阅读
- reactjs - 将设置按钮反应为禁用状态
- java - 如何以编程方式更改分频器偏差
- android - Flutter Plugin manifestPlaceholders 错误
- angular - 如何将授权令牌添加到 HTTP 请求
- python - 在 ElasticSearch 上索引 SQLAlchemy 模型
- rest - 对 Jenkins /reload 或 /restart 的纯 Java REST API POST 调用总是返回状态 403 禁止,但可以工作
- bash - 使用 awk 操作来自两个来源的数据
- java - 用于 JSON 整数数组的 PACT
- python - 如何将标签添加到特定位置并将值的总和作为绘图的大小
- ruby-on-rails - Dockerfile cmd 返回 Yarn 完整性错误,但 Docker 运行正常