首页 > 解决方案 > 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++cstruct

解决方案


你可以用 C++20[[no_unique_address]]一些诡计来做到这一点。但是,这并不能保证会导致较小的类型,因此我仍然建议您使用#defines

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;        
};

推荐阅读