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

后端 未结 4 1876
被撕碎了的回忆
被撕碎了的回忆 2020-12-11 21:58

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;         


        
4条回答
  •  情歌与酒
    2020-12-11 22:42

    To get the total field size without retyping each struct member you can use an X Macro

    First define all the fields

    #define LIST_OF_FIELDS_OF_This_Should_Fail    \
        X(int, a)          \
        X(char, b)         \
        X(int, c)
    
    #define LIST_OF_FIELDS_OF_This_Should_Succeed \
        X(long long, a)    \
        X(long long, b)    \
        X(int, c)          \
        X(int, d)          \
        X(int, e)          \
        X(int, f)
    

    then declare the structs

    struct This_Should_Fail {
    #define X(type, name) type name;
        LIST_OF_FIELDS_OF_This_Should_Fail
    #undef X
    };
    
    struct This_Should_Succeed {
    #define X(type, name) type name;
        LIST_OF_FIELDS_OF_This_Should_Succeed
    #undef X
    };
    

    and check

    #define X(type, name) sizeof(This_Should_Fail::name) +
    static_assert(sizeof(This_Should_Fail) == LIST_OF_FIELDS_OF_This_Should_Fail 0);
    #undef X
    
    #define X(type, name) sizeof(This_Should_Succeed::name) +
    static_assert(sizeof(This_Should_Succeed) == LIST_OF_FIELDS_OF_This_Should_Succeed 0);
    #undef X
    

    or you can just reuse the same X macro to check

    #define X(type, name) sizeof(a.name) +
    {
        This_Should_Fail a;
        static_assert(sizeof(This_Should_Fail) == LIST_OF_FIELDS_OF_This_Should_Fail 0);
    }
    {
        This_Should_Succeed a;
        static_assert(sizeof(This_Should_Succeed) == LIST_OF_FIELDS_OF_This_Should_Succeed 0);
    }        
    #undef X
    

    See demo on compiler explorer

    For more information about this you can read Real-world use of X-Macros

提交回复
热议问题