How to combine static_assert with sizeof and stringify?

后端 未结 4 1957
忘掉有多难
忘掉有多难 2020-12-30 01:55

Memory usage is quite critical in my application. Therefore I have specific asserts that check for the memory size at compile time and give a static_assert if the size is d

4条回答
  •  星月不相逢
    2020-12-30 02:45

    Here's an alternative header-only solution if you can modify the struct's definition a bit and don't mind some ugliness.

    template 
    struct _MyStruct {
        static_assert(RealSize == ExpectedSize, "size is invalid");
    
        int x;
    };
    
    typedef _MyStruct), 4> MyStruct;
    

    clang outputs:

    prog.cpp:4:5: error: static_assert failed "size is invalid"
        static_assert(RealSize == ExpectedSize, "size is invalid");
        ^             ~~~~~~~~~~~~~~~~~~~~~~~~
    prog.cpp:12:14: note: in instantiation of template class '_MyStruct<4, 8>' requested here
        MyStruct m;
    

    One caveat here is that the check will only occur if you instantiate the type somewhere -- just using a pointer won't trigger the error, so definitely not a great fit for all situations!

提交回复
热议问题