Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing sizeof(T) at compile time [duplicate]

Tags:

c++

sizeof

Possible Duplicate:
Is it possible to print out the size of a C++ class at compile-time?

Can I output the size of an object at compile time? Since the compiler already has this information when it is compiling a source file, can I see it (at compile time) rather than going through the lengthy process of outputting the size somewhere in my application's console or the debug output window?

This will be very useful especially when I am able to compile single source files which saves me tremendous amounts of time when working on large projects.

like image 672
Samaursa Avatar asked Oct 28 '11 15:10

Samaursa


1 Answers

Yes. The possible duplicate prints the size as error message, which means the compilation will not succeed.

However, my solution prints the size as warning message, which means, it will print the size, and the compilation will continue.

template<int N> 
struct print_size_as_warning
{ 
   char operator()() { return N + 256; } //deliberately causing overflow
};

int main() {
        print_size_as_warning<sizeof(int)>()();
        return 0;
}

Warning message:

prog.cpp: In member function ‘char print_size_as_warning<N>::operator()() [with int N = 4]’:
prog.cpp:8:   instantiated from here
prog.cpp:4: warning: overflow in implicit constant conversion

Demo : http://www.ideone.com/m9eg3

Note : the value of N in the warning message is the value of sizeof(int)


The above code is improved one, and my first attempt was this:

template<int N> 
struct _{ operator char() { return N+ 256; } }; //always overflow

int main() {
        char(_<sizeof(int)>());
        return 0;
}

Warning message:

prog.cpp: In member function ‘_<N>::operator char() [with int N = 4]’:
prog.cpp:5:   instantiated from here
prog.cpp:2: warning: overflow in implicit constant conversion

Demo : http://www.ideone.com/mhXjU

The idea is taken from my previous answer to this question:

  • Calculating and printing factorial at compile time in C++
like image 104
Nawaz Avatar answered Sep 21 '22 13:09

Nawaz