【问题标题】:Printing sizeof(T) at compile time [duplicate]在编译时打印 sizeof(T) [重复]
【发布时间】:2011-12-17 09:32:14
【问题描述】:

可能重复:
Is it possible to print out the size of a C++ class at compile-time?

我可以在编译时输出对象的大小吗?由于编译器在编译源文件时已经拥有此信息,我是否可以查看它(在编译时)而不是通过在某处输出大小的冗长过程在我的应用程序的控制台或调试输出窗口中?

这将非常有用,尤其是当我能够编译单个源文件时,这为我在处理大型项目时节省了大量时间。

【问题讨论】:

  • 这是您要找的吗? stackoverflow.com/questions/2008398/…
  • 许多编译器都有#pragma 或其他可用于在编译期间输出值的指令。您必须检查编译器的文档。不幸的是,我不知道如何让编译器在生成输出之前评估表达式。
  • 我不回答,因为我不完全确定,但我认为答案是否定的。
  • @MichaelKrelin-hacker,你为什么认为这是一个不同的问题?在我看来完全一样。
  • Samaursa,不要因为没有通过搜索找到它而感到难过,也不要亲自结束。使用不同的搜索词提出不同的问题是一件好事,但将所有答案集中在一个地方也很好。

标签: c++ sizeof


【解决方案1】:

是的。可能的重复将大小打印为 error 消息,这意味着编译不会成功。

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

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)的值


上面的代码是改进的一个,我的第一次尝试是这样的:

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

演示:http://www.ideone.com/mhXjU

这个想法来自我之前对这个问题的回答:

【讨论】:

    猜你喜欢
    • 2014-01-25
    • 2017-06-30
    • 2019-09-28
    • 1970-01-01
    • 1970-01-01
    • 2012-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多