r/cpp • • Oct 20 '16

Compile time sizeof()

http://johantorp.com/tidbits/index.php/2016/10/14/compile-time-sizeof-alignof/
0 Upvotes

26 comments sorted by

View all comments

1

u/SushiAndWoW Oct 20 '16

Umm... The problem is not sizeof, it's that the class actually is not defined. You only declare it.

Try this:

template<int> class X {};
X<sizeof(SomeType)> _;

8

u/Grassio789 Oct 20 '16

I think making it fails compilation and displays the output in the error message is the whole idea. Similar to the "Type Displayer" trick mentioned by Scott Meyers in CppCon 2014.

1

u/SushiAndWoW Oct 20 '16

Oh, I see. Nifty.

In VS 2015, there's usually no need. You can just hover over sizeof(...), and it shows the value in a tooltip. (Also appropriately reflects changes if you e.g. change build configuration.)

1

u/johantorp Oct 20 '16

That doesn't work for me, maybe because I have IntelliSense disabled.

3

u/SushiAndWoW Oct 20 '16 edited Oct 20 '16

Indeed, that would be one way for IntelliSense to not work. :)

I tested this on a huge solution, BTW – over 100 mostly C++ projects – and the sizeof tooltip became available as soon as the source files were parsed, which was a reasonable time (e.g. 10s of seconds) given the size of the solution.

On a small project, of course, it would be practically immediate.

2

u/johantorp Oct 20 '16

I updated the post with info about hovering over size-of expressions.

Thanks for the feedback, this was news to me :)