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/ti-gars Oct 24 '16

I prefer the switch trick, worked with all compilers I tried, not like the template<int> trick...

struct X { .. };
int i;
switch(i)
{
case sizeof(X):
case sizeof(X): // outputs an error with the size of being used twice
break;
}

1

u/johantorp Oct 24 '16

Interesting, thanks for sharing.

Which compiler does this work on where template<int> struct doesn't? The template<int> trick works on gcc, clang and MSVC, which are all the compilers I care about :) template<int> does not work on Intel's compiler but neither does your sizeof version..

Also, the sizeof version is significantly more verbose and thus cumbersome to use...

1

u/ti-gars Oct 24 '16

there's been versions (don't remember which ones) of both clang and msvc that were not outputing the sizeof size :-/ made me switch at that point.

1

u/johantorp Oct 24 '16

Ah, I think you were using function templates then. They only worked on one compiler IIRC, can't recall which. class/struct templates has always worked on all three as far as I can remember.

1

u/ti-gars Oct 24 '16

nope, definitely the same struct trick :-) anyway nice trick!