C 或 C++ 中没有 ifdef 的结构

Xee*_*ych 2 c c++ struct

有一些 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
}
Run Code Online (Sandbox Code Playgroud)

原因是为了减少未使用选项的结构大小。有很多ifdef!到处!

有没有一种 C++ 方法可以摆脱这些 ifdef,保留编译器优化未使用字段的能力?也许使用模板、使用或 CRTP 继承?

Cal*_*eth 8

您可以在 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;
};
Run Code Online (Sandbox Code Playgroud)

在 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;        
};
Run Code Online (Sandbox Code Playgroud)