Note that there are some explanatory texts on larger screens.

plurals
  1. POBetter Message For `static_assert` on Object Size
    text
    copied!<p>I've been using <code>static_assert</code> (and the variants before standardization) quite heavily. One use that I'm sure many of us have them put to is ensuring that the size of sensitive data structures remain as assumed across platforms and configurations. For example:</p> <pre><code>class SizeSensitiveClass { // ... }; static_assert (sizeof(SizeSensitiveClass) == 18, "Check the size!"); </code></pre> <p>Now, I've written a convenience macro to help with this particular use:</p> <pre><code>#define STATIC_ASSERT_SIZE(T, sz) (sizeof(T) == (sz), "Size of '" #T "' doesn't match the expected value.") </code></pre> <p>Used like this:</p> <pre><code>STATIC_ASSERT_SIZE (SizeSensitiveClass, 18); </code></pre> <p>Which produces this output: (at compile time, obviously, in form of compile error)</p> <blockquote> <p>Size of 'SizeSensitiveClass' doesn't match the expected value.</p> </blockquote> <p>This is OK and nice, but I was wondering whether I can extend the implementation of this macro (keeping the interface intact) to output the <em>current size</em> and the <em>expected size</em> of the data structure as well. Ideally, the output should look something like:</p> <blockquote> <p>Size of 'SizeSensitiveClass' doesn't match the expected value (20 vs. 18).</p> </blockquote> <p>Even the current size would be extremely convenient. Is this possible?</p> <p>I'm using VC12 (Visual C++ 2013) and GCC 4.8.1. I'd appreciate any solutions/techniques/methods that would be portable to at least these two.</p> <p>I should mention that I have tried the common "stringize" trick, but it doesn't work (as one would have expected it not to.) It just produces the literal string <code>sizeof(T)</code> in the output.</p> <p>I have a vague notion that this might be implemented using <code>constexpr</code>s (to generate the message string) but I'm not familiar with them.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload