可以打印编译时间常数,例如不需要运行代码就可以使用sizeof
。例如:
class X
{
int x;
int y;
int z;
};
template <int i>
class foo;
foo<sizeof(X)> x;
错误消息清楚地讲述了sizeof
表达式的值:
test.cpp:12:16: error: aggregate ‘foo<12> x’ has incomplete type and cannot be defined
foo<sizeof(X)> x;
Works为offsetof
为好。您还可以查询多个偏移一次:
#include <cstddef>
foo<offsetof(X,X::x)> offset_x;
foo<offsetof(X,X::y)> offset_y;
foo<offsetof(X,X::z)> offset_z;
结果:
test.cpp:15:23: error: aggregate ‘foo<0> offset_x’ has incomplete type and cannot be defined
foo<offsetof(X,X::x)> offset_x;
^
test.cpp:16:23: error: aggregate ‘foo<4> offset_y’ has incomplete type and cannot be defined
foo<offsetof(X,X::y)> offset_y;
^
test.cpp:17:23: error: aggregate ‘foo<8> offset_z’ has incomplete type and cannot be defined
foo<offsetof(X,X::z)> offset_z;
来源
2014-09-19 22:16:39
Csq
“无运行代码” - 阅读编译器手册? – Galik 2014-09-19 21:53:21
您可以在编译时使用'sizeof',所以不需要'printf'。 – Jarod42 2014-09-19 22:15:18