c++ - 如何在编译时检查结构的大小?

我想添加在编译期间检查结构大小以确保它是预定义大小的代码。例如,当我移植此代码或在编译期间从结构中添加/删除项目时,我想确保此结构的大小为 1024 字节:

#pack(1)
struct mystruct
{
    int item1;
    int item2[100];
    char item3[4];
    char item5;
    char padding[615];
 }

我知道如何在运行时使用如下代码来执行此操作:

 if(sizeof(mystruct) != 1024)
 { 
     throw exception("Size is not correct");
 }

但是如果我在运行时这样做是浪费处理。我需要在编译期间执行此操作。

如何在编译期间执行此操作?

最佳答案

编译时可以查看大小:

static_assert (sizeof(mystruct) == 1024, "Size is not correct");

为此,您需要 C++11。 Boost 有一个针对 c++11 之前的编译器的解决方法:

BOOST_STATIC_ASSERT_MSG(sizeof(mystruct) == 1024, "Size is not correct");

见 the documentation .

https://stackoverflow.com/questions/19401887/

相关文章:

c++ - 如何让我的类(class)成为 google-test 类(class)的 friend

c++ - std::pair 的顺序是否明确?

c++ - VS2012 在 64 位目标中 vector 的性能不佳

c++ - 如何设置 QMainWindow 标题

c++ - 如何强制 gcc 链接未使用的静态库

c++ - 计算机如何进行浮点运算?

c++ - C 和 C++ 中的 1LL 或 2LL 是什么?

c++ - 访问另一个子类中基类的 protected 成员

c++ - 我收到错误 "invalid use of incomplete type ' 类映射'

c++ - std::map 如何提供常量 size() 操作?