在编译时打印sizeof(T) [英] Printing sizeof(T) at compile time

查看:384
本文介绍了在编译时打印sizeof(T)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

是否可以在编译时打印出C ++类的大小?

我可以在编译时输出对象的大小吗?由于编译器在编译源文件时已经有了这些信息,我可以查看 (在编译时),而不是经过漫长的输出大小的过程在我的应用程序的控制台或调试输出窗口?

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.

推荐答案

是的。

但是,我的解决方案打印的大小为错误 >警告消息,这意味着它将打印大小,并且编译将继续。

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;
}

警告讯息:

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



http://www.ideone.com/m9eg3

注意:警告消息中的N值是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;
}

警告讯息:

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

演示:< a href =http://www.ideone.com/mhXjU> 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++

这篇关于在编译时打印sizeof(T)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆