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

标签 c++ data-structures static-assert

我想添加在编译期间检查结构大小以确保它是预定义大小的代码。例如,当我移植此代码或在编译期间从结构中添加/删除项目时,我想确保此结构的大小为 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 .

关于c++ - 如何在编译时检查结构的大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19401887/

相关文章:

c++ - 具有非类型模板参数的构造函数

c++ - 代码块问题

python - 如何在Python中正确实现不相交集数据结构来查找跨越森林?

algorithm - 给定一个随机顺序的整数数组,你必须找到最小交换次数才能将其转换为循环排序数组

c++ - static_assert 无法将 const char* 模板参数识别为 constexpr : g++ bug?

c++ - 通过 decltype 表达式调用时 static_assert 是否应该工作?

c++ - 使用ctags获取类继承

c++ - 将结构的枚举传递给其他函数并分配值

c - 简单地创建一个数据结构,它怎么会发生段错误?

c++ - 如何检查模板参数是否为 2 的幂?