How to combine static_assert with sizeof and stringify?

后端 未结 4 1948
忘掉有多难
忘掉有多难 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:41

    I'd use dispatching on a function template to do the checking:

    #include 
    
    template 
    void check_size() {
      static_assert(ExpectedSize == RealSize, "Size is off!");
    }
    
    struct foo
    {
      char bla[16];
    };
    
    int main()
    {
      check_size();
      return 0;
    }
    

    Results in:

    In instantiation of ‘void check_size() [with ToCheck = foo; long unsigned int ExpectedSize = 8ul; long unsigned int RealSize = 16ul]’:
    bla.cpp:15:22:   required from here
    bla.cpp:5:1: error: static assertion failed: Size is off!
    

    The debugging information is in the template parameters of the back-trace.

    If this is truly better, you will have to decide and it also depends on the compiler. It also enables you to hide the expected size with a template map, to sum up to a max size and other fancy things.

提交回复
热议问题