1

I have a structure obj and a function (in separate file) that populates this structure with some values. Due to the system design this function couldn't be a part of the structure (which is generated by a script). Eventually the structure may change, so the function should be updated accordingly. The problem is that the developer that changes the structure might forget to update the corresponding function, and the compiler wouldn't remind about that (if some parameters will be added, and existing parameters remain the same).

The best idea I have in mind is to check sizeof(obj) at compile time and compare it to the previous known size. When the structure will be changed in size, the compiler would throw an error, so the developer will look closer at this function and update it.

This question has the solution for STATIC_ASSERT. The problem is that the compiler doesn't print current size of the structure. So the developer wouldn't know what to set as a new expected structure size.

I want something like this:

STATIC_ASSERT(sizeof(obj) == 1234)

And the compiler should output something like:

error: ... sizeof(obj) is 5678 ...

If the sizeof(obj) is as expected, the compiler shouldn't print anything.

This solution prints warning with the sizeof() value, but in my build environment warnings are treated as errors, so I couldn't apply this solution: my build will be failing all the time because of that warning.

So how could I make the compiler raise an error or warning only if the sizeof is not as expected?

Heavy
  • 1,861
  • 14
  • 25

1 Answers1

2

One way to "display" value at compile time is in the error:

template <std::size_t N> struct Debug; // No definition

template <> struct Debug<1234> {}; // Definition for "old" sizeof;

template struct Debug<sizeof(obj)>; // Issue error if definition is missing

Demo without error
Demo with error

Error message is similar to:

error: explicit instantiation of ‘struct Debug<5678ul>’ before definition of template

Jarod42
  • 203,559
  • 14
  • 181
  • 302
  • Thanks, this does the trick! But it doesn't work inside functions, which would be more consistent. – Heavy May 10 '19 at 22:28
  • 1
    Declarations (and explicit instantiation) should go in namespace scope, indeed. in function scope, you may declare variable `Debug d; Issue error if definition is missing`. – Jarod42 May 10 '19 at 22:30
  • You probably need to change to something like `template struct Debug;` if you want to extend checks to several classes. – Jarod42 May 10 '19 at 22:34