可能重复:
是否可以在编译时打印出C++类的大小?
我可以在编译时输出对象的大小吗?由于编译器在编译源文件时已经有了这些信息,我可以看到它(在编译时)而不是经历在我的应用程序控制台或调试输出窗口中某处输出大小的漫长过程吗?
这将非常有用,尤其是当我能够编译单个源文件时,这为我在处理大型项目时节省了大量时间.
Naw*_*waz 20
是.可能的重复项将大小打印为错误消息,这意味着编译将不会成功.
但是,我的解决方案将大小打印为警告消息,这意味着,它将打印大小,编译将继续.
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;
}
Run Code Online (Sandbox Code Playgroud)
警告信息:
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
Run Code Online (Sandbox Code Playgroud)
演示:http://www.ideone.com/m9eg3
注意:警告消息中的N值是sizeof(int)的值
上面的代码是改进的,我的第一次尝试是这样的:
template<int N>
struct _{ operator char() { return N+ 256; } }; //always overflow
int main() {
char(_<sizeof(int)>());
return 0;
}
Run Code Online (Sandbox Code Playgroud)
警告信息:
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
Run Code Online (Sandbox Code Playgroud)
演示:http://www.ideone.com/mhXjU
这个想法来自我之前对这个问题的回答: