Search code examples
c++structpaddingstatic-assert

Compile-time check to make sure that there is no padding anywhere in a struct


Is there a way to write a compile-time assertion that checks if some type has any padding in it?

For example:

struct This_Should_Succeed
{
    int a;
    int b;
    int c;
};

struct This_Should_Fail
{
    int a;
    char b;
    // because there are 3 bytes of padding here
    int c;
};

Solution

  • Since C++17 you might be able to use std::has_unique_object_representations.

    #include <type_traits>
    
    static_assert(std::has_unique_object_representations_v<This_Should_Succeed>); // succeeds
    static_assert(std::has_unique_object_representations_v<This_Should_Fail>); // fails
    

    Although, this might not do exactly what you want it to do. For instance, it could fail if your struct contains

    • a bool in an ABI where any nonzero value of a byte is true, not just 0x01, or
    • an IEC 559 float because there are multiple representations of zero and NaN, or
    • a pointer on an architecture with multiple null pointer representations, or
    • any fundamental type with padding, or
    • other such types that don't have unique object representations.

    Check the linked cppreference page for details, and see What type will make "std::has_unique_object_representations" return false?