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;
};
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
bool
in an ABI where any nonzero value of a byte is true
, not just 0x01
, orfloat
because there are multiple representations of zero and NaN, orCheck the linked cppreference page for details, and see What type will make "std::has_unique_object_representations" return false?