Printing sizeof(T) at compile time [duplicate]

淺唱寂寞╮ 提交于 2019-11-30 13:05:13
Nawaz

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:

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!