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

后端 未结 4 1874
被撕碎了的回忆
被撕碎了的回忆 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:28

    Edit: Check Kerndog73's answer.

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

    Yes.

    You can sum the sizeof of all members and compare it to the size of the class itself:

    static_assert(sizeof(This_Should_Succeed) == sizeof(This_Should_Succeed::a)
                                               + sizeof(This_Should_Succeed::b)
                                               + sizeof(This_Should_Succeed::c));
    
    static_assert(sizeof(This_Should_Fail)    != sizeof(This_Should_Fail::a)
                                               + sizeof(This_Should_Fail::b)
                                               + sizeof(This_Should_Fail::c));
    

    This unfortunately requires explicitly naming the members for the sum. An automatic solution requires (compile time) reflection. Unfortunately, C++ language has no such feature yet. Maybe in C++23 if we are lucky. For now, there are solutions based on wrapping the class definition in a macro.

    A non-portable solution might be to use -Wpadded option provided by GCC, which promises to warn if structure contains any padding. This can be combined with #pragma GCC diagnostic push to only do it for chosen structures.


    type I'm checking, the type is a template input.

    A portable, but not fully satisfactory approach might be to use a custom trait that the user of the template can use to voluntarily promise that the type does not contain padding allowing you to take advantage of the knowledge.

    The user would have to rely on explicit or pre-processor based assertion that their promise holds true.

提交回复
热议问题