constexpr and endianness

后端 未结 8 536
無奈伤痛
無奈伤痛 2020-12-24 12:42

A common question that comes up from time to time in the world of C++ programming is compile-time determination of endianness. Usually this is done with barely portable #if

8条回答
  •  再見小時候
    2020-12-24 12:55

    I was able to write this:

    #include 
    
    class Endian
    {
    private:
        static constexpr uint32_t uint32_ = 0x01020304;
        static constexpr uint8_t magic_ = (const uint8_t&)uint32_;
    public:
        static constexpr bool little = magic_ == 0x04;
        static constexpr bool middle = magic_ == 0x02;
        static constexpr bool big = magic_ == 0x01;
        static_assert(little || middle || big, "Cannot determine endianness!");
    private:
        Endian() = delete;
    };
    

    I've tested it with g++ and it compiles without warnings. It gives a correct result on x64. If you have any big-endian or middle-endian proccesor, please, confirm that this works for you in a comment.

提交回复
热议问题