可以打印編譯時間常數,例如不需要運行代碼就可以使用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