位域的默认成员初始化和预处理器指令中 constexpr 静态布尔值的使用

问题描述

我需要使用 bitfields 统一初始化认初始化我的类的 c++11,但出现编译器错误。有人可以建议解决此问题的方法。另外我想知道是否可以在 constexpr static bool 指令中传递 #if 变量。这是一个示例代码

#include <iostream>
#include <endian.h>

class Endiann {
public:

#ifdef __linux__

#if __BYTE_ORDER == __BIG_ENDIAN
    constexpr static bool BIG_ENDIAN_PRO = true
#elif __BYTE_ORDER == __LITTLE_ENDIAN
    constexpr static bool BIG_ENDIAN_PRO = false
#endif

#endif

#ifdef __WIN32__

#if __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
    constexpr static bool BIG_ENDIAN_PRO = true
#elif __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
    constexpr static bool BIG_ENDIAN_PRO = false
#endif

#endif

    static void swap_bytes(char *buff,int32_t sizee) {
        char *start = buff,*end = buff + sizee - 1;

        while(start < end) {
            char swap = *start;
            *start = *end;
            *end = swap;

            ++start;
            --end;

        }
    }
};

constexpr bool Endiann::BIG_ENDIAN_PRO;

struct MSG {
    int16_t a {};
    
#if Endiann::BIG_ENDIAN_PRO // getting compiler error here
    int16_t b:6 {};
    int16_t c:6 {};
    int16_t d:4 {};
#else
    int16_t d:4 {};
    int16_t c:6 {};
    int16_t b:6 {};
#endif
};

int main() {
    MSG msg; // I kNow I can use uniform initialization here,but for better assurance I'm using uniform initialization in the struct itself for each member variable
    
    return 0;
}

我正在使用 gcc 并且它仅支持 c++11 标准

解决方法

#if 指令由编译前运行的预处理器解析,因此您不能在指令中传递任何 C++ 变量

您仍然可以使用 constexpr static bool BIG_ENDIAN_PRO = true; 声明您的 C++ 变量(缺少 bool)。对于您的 #if,您可以使用 #if __BYTE_ORDER == __BIG_ENDIAN

对于初始化,您可以删除初始化程序并在结构中添加以下内容:

MSG(): a(0),b(0),c(0),d(0){}