Pat*_*ick 17 c++ static-assert visual-studio-2010 stringify c++11
内存使用在我的应用程序中非常重要.因此,我有特定的断言,在编译时检查内存大小,如果大小与我们之前认为正确的大小不同,则给出static_assert.
我已经定义了一个像这样的宏:
#define CHECKMEM(mytype, size) static_assert((sizeof(objectType) == size)), "Size incorrect for " #mytype "!");
Run Code Online (Sandbox Code Playgroud)
这个宏使得编写它非常容易:
CHECKMEM(Book,144);
CHECKMEM(Library,80);
Run Code Online (Sandbox Code Playgroud)
问题是当这个static_assert出现时,可能很难找出新的大小应该是什么(例如通过使用隐藏的编译器选项"/ d1 reportAllClassLayout").如果我可以包含实际大小会更方便,所以代替:
Book的大小不正确!
它会显示出来
Book的大小不正确!(预计144,大小为152)
我试着写这样的东西:
#define CHECKMEM(mytype, size) static_assert((sizeof(objectType) == size)), "Size incorrect for " #mytype "! (expected" #size ", size is " #sizeof(mytype) ")");
Run Code Online (Sandbox Code Playgroud)
但是你不能在函数调用中使用stringize(#)运算符.
我也尝试添加双串联技巧,如下所示:
#define STR1(x) #x
#define STR2(x) STR1(x)
#define CHECKMEM(mytype, size) static_assert((sizeof(objectType) == size)), "Size incorrect for " #mytype "! (expected" #size ", size is " STR2(sizeof(mytype)) ")");
Run Code Online (Sandbox Code Playgroud)
但不是打印size is 152它打印size is sizeof(Book).
有没有办法在static_assert中将sizeof的结果字符串化?
pmr*_*pmr 18
我将在函数模板上使用调度来进行检查:
#include <cstddef>
template <typename ToCheck, std::size_t ExpectedSize, std::size_t RealSize = sizeof(ToCheck)>
void check_size() {
static_assert(ExpectedSize == RealSize, "Size is off!");
}
struct foo
{
char bla[16];
};
int main()
{
check_size<foo, 8>();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
结果是:
In instantiation of ‘void check_size() [with ToCheck = foo; long unsigned int ExpectedSize = 8ul; long unsigned int RealSize = 16ul]’:
bla.cpp:15:22: required from here
bla.cpp:5:1: error: static assertion failed: Size is off!
Run Code Online (Sandbox Code Playgroud)
调试信息位于反向跟踪的模板参数中.
如果这真的更好,你将不得不做出决定,这也取决于编译器.它还允许您使用模板地图隐藏预期大小,总结最大尺寸和其他奇特的东西.
根据您的编译器,模板可能会有所帮助:
template<int s, int t> struct check_size {
static_assert(s == t, "wrong size");
};
check_size<2+2, 5> doubleplusungood;
Run Code Online (Sandbox Code Playgroud)
gcc 输出:
prog.cpp: In instantiation of 'check_size<4, 5>':
prog.cpp:5:20: instantiated from here
prog.cpp:2:3: error: static assertion failed: "wrong size"
Run Code Online (Sandbox Code Playgroud)