在编译时断言 sizeof(obj) 并在不匹配时打印实际大小 (c++98)

Assert sizeof(obj) at compile time and print the actual size if it doesn't match (c++98)

我有一个结构 obj 和一个用一些值填充这个结构的函数(在单独的文件中)。由于系统设计,此功能不能成为结构的一部分(由脚本生成)。 最终结构可能会改变,所以功能应该相应地更新。问题是开发者改变结构可能忘记更新相应的函数,编译器不会提醒(如果会增加一些参数,现有参数保持不变)。

我想到的最好的想法是在编译时检查 sizeof(obj) 并将其与以前已知的大小进行比较。当结构的大小发生变化时,编译器会抛出一个错误,因此开发人员会仔细研究这个函数并更新它。

This questionSTATIC_ASSERT 的解决方案。问题是编译器不打印结构的 current 大小。因此开发人员不知道将什么设置为新的预期结构大小。

我想要这样的东西:

STATIC_ASSERT(sizeof(obj) == 1234)

编译器应该输出如下内容:

error: ... sizeof(obj) is 5678 ...

如果 sizeof(obj) 符合预期,编译器不应打印任何内容。

This solution 使用 sizeof() 值打印警告,但在我的构建环境中,警告被视为错误,因此我无法应用此解决方案:我的构建将一直失败,因为那个警告。

那么,只有当 sizeof 与预期不符时,我如何才能让编译器引发错误或警告

编译时 "display" 值的一种方法是在错误中:

template <std::size_t N> struct Debug; // No definition

template <> struct Debug<1234> {}; // Definition for "old" sizeof;

template struct Debug<sizeof(obj)>; // Issue error if definition is missing

Demo without error
Demo with error

错误消息类似于:

error: explicit instantiation of ‘struct Debug<5678ul>’ before definition of template