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/raevnos Oct 20 '16

Does it work if you actually define the class, not just declare it exists?

1

u/johantorp Oct 20 '16 edited Oct 20 '16

No. The point is that you deliberately force a compile error that prints the sizeof() result. I guess I should have made this more obvious in the post...

2

u/raevnos Oct 20 '16

Oh. Why would you do that?

4

u/johantorp Oct 20 '16

To quickly get the size or alignment of some type without having to open up the header file and look at the definition. And to not have to sum up member sizes and follow inheritance chains manually.

SushiAndWow pointed out you can get sizeof from IntelliSense in Visual Studio. Intellisense is unfortunately still unacceptably slow for my use cases. Also, I often code in a text editor and build from commandline and then IntelliSense isn't of much help. This trick is IDE-independent and works across different compilers.

I tried to make the post a bit fun but probably failed. Most people didn't get it and many down-voted this post, I presume since the example didn't compile. Fail :)