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

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