Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
342 views
in Technique[技术] by (71.8m points)

c++ - default member initialization for bitfields and usage of constexpr static bool in preprocessor directives

I need to default initialize bitfields of my class using c++11 uniform initialization but getting compiler error. Can somebody suggest a work around for this issue. Also I want to know is it possible to pass a constexpr static bool variable in #if directive. This is a sample code:

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

I'm using gcc and it supports only c++11 standard


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The #if directive is resolved by the preprocessor which runs before compiling so no you can't pass any C++ variable in a directive

You can still declare your C++ variables with constexpr static bool BIG_ENDIAN_PRO = true; (bool was missing). For your #if you could use #if __BYTE_ORDER == __BIG_ENDIAN

For the initialization you could remove the initializers and add the following in your struct:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...