Archive for May, 2011

Tricking the Compiler into Giving You Size Information

Posted in Programming on May 3rd, 2011 by Chris – Be the first to comment

Figured out an interesting way to get the compiler to tell you the size of a class/structure.. at compile time!

#define SHOW_SIZE(type) \
template<size_t _size> class DbgSize##type {}; \
struct t_b##type {}; \
DbgSize##type<sizeof(t_b##type)> b##type = DbgSize##type<sizeof(type)>();

struct SomeStruct { char data[55]; };

I get the following in Visual Studio:
error C2440: 'initializing' : cannot convert from 'DbgSizeSomeStruct<_size>' to 'DbgSizeSomeStruct<_size>'

See what it did there? We “trick” the compiler to tell us the template arguments, which we have set to the size of the structure.

As a note, this does work in SN, though the error is a bit.. cleaner?

Much credit should be given to my coworker, Daniel Silver, who came up with the initial idea for this.