Sunday, May 3, 2015

Compile-time sizeof() in C++

Runtime sizeof() is nice for lots of reasons, but often when optimizing you don't want to build and run your entire program just to find out whether a potential optimization reduced the size of a class or struct.  This is a great trick someone taught me forever ago.  I've used it a ton to help with cross-platform optimizations in Skullgirls.

// compile-time sizeof()! Aww yeah.
template<int s> struct Wow { int x; };
Wow<sizeof(MyClass)> unused = 5;

and when you compile the file you get an error like

1>.\file.cpp(32) : error C2440: 'initializing' : cannot convert from 'int' to 'Wow<s>'
1>        with
1>        [
1>            s=1044
1>        ]
1>        No constructor could take the source type, or constructor overload resolution was ambiguous

and there's the size of your class!

No comments:

Post a Comment