Search code examples
c++11unionsizeofc11static-assert

the most clean way to static_assert 3 or more items in oneline


How to static_assert 3 items to be same at compile time like this.

union
{
    std::uint32_t   multibyte;
    std::uint8_t    bytes[4];
} test;

static_assert(sizeof(test) == sizeof(test.multibyte) == sizeof(test.bytes), "Union size mismatch.");

So of course the static_assert here fails because the last check will be 1 == 4. Is there more clean way besides

static_assert(sizeof(test.bytes) == sizeof(test.multibyte) && sizeof(test) == sizeof(test.bytes), "Union size mismatch.");

Solution

  • You could write a struct for that:

    template<typename...> struct AllSame;
    
    template<typename Arg1, typename Arg2, typename... Args>
    struct AllSame<Arg1, Arg2, Args...>
    {
        static constexpr bool value = sizeof(Arg1) == sizeof(Arg2) && AllSame<Arg1, Args...>::value;
    };
    
    template<typename Arg>
    struct AllSame<Arg>
    {
            static constexpr bool value = true;
    };
    

    Not tested, might contain errors.