我试图在编译时输出结构成员的偏移量。我需要知道偏移量,稍后我想添加一个#error 以确保成员保持相同的偏移量。我已经在 VS 中看到了几种工作方法,但我使用的是 GCC,但它们不能正常工作。
谢谢!
您可以将offsetof
宏与 C++11static_assert
功能一起使用,如下所示:
struct A {
int i;
double db;
...
unsigned test;
};
void TestOffset() {
static_assert( offsetof( A, test ) == KNOWN_VALUE, "The offset of the \"test\" variable must be KNOWN_VALUE" );
}
把它和你的文件放在同一个文件中main()
:
template <bool> struct __static_assert_test;
template <> struct __static_assert_test<true> {};
template <unsigned> struct __static_assert_check {};
#define ASSERT_OFFSETOF(class, member, offset) \
typedef __static_assert_check<sizeof(__static_assert_test<(offsetof(class, member) == offset)>)> PROBLEM_WITH_ASSERT_OFFSETOF ## __LINE__
这在你的里面main()
:
ASSERT_OFFSETOF(foo, member, 12);
即使您没有 C++11,这也应该可以工作。如果你这样做,你可以定义ASSERT_OFFSETOF
为:
#define ASSERT_OFFSETOF(class, member, offset) \
static_assert(offsetof(class, member) == offset, "The offset of " #member " is not " #offset "...")