给定以下结构:
struct ExampleStruct {
char firstMember[8];
uint64_t secondMember;
};
Run Code Online (Sandbox Code Playgroud)
有没有办法写一个静态断言来验证偏移量secondMember是8个字节的倍数?
如果您的类型具有标准布局,则可以使用offsetof宏:
#include <cstddef>
static_assert(offsetof(ExampleStruct, secondMember) % 8 == 0, "Bad alignment");
Run Code Online (Sandbox Code Playgroud)
这个offsetof宏导致一个常量表达式,如果不满足条件,可以使用静态断言产生转换错误.
Offsetof您可以使用图书馆offsetof带来的marco cstddef.这里我首先得到偏移量,然后我使用模运算符来检查它是否是8的倍数.然后,如果余数为0,则偏移量确实是8个字节的倍数.
// Offset.cpp
#include <iostream>
#include <string>
#include <cstddef>
#include <stdarg.h>
struct ExampleStruct {
char firstMember[8];
uint64_t secondMember;
};
int main()
{
size_t offset = offsetof(ExampleStruct, secondMember);
if(offset%8==0)
std::cout << "Offset is a multiple of 8 bytes";
}
Run Code Online (Sandbox Code Playgroud)
在这里演示
Offsetof 同 static_assert或者通过这个问题的背景,目标是拥有一个static_assert.嗯,这几乎是一回事:
// OffsetAssert.cpp
#include <iostream>
#include <string>
#include <cstddef>
#include <stdarg.h>
struct ExampleStruct {
char firstMember[8];
uint64_t secondMember;
};
int main()
{
size_t offset = offsetof(ExampleStruct, secondMember); // Get Offset
static_assert(offsetof(ExampleStruct, secondMember)%8==0,"Not Aligned 8 Bytes"); // Check if the offset modulus 8 is remainer 0 , if so it is a multiple of 8
std::cout << "Aligned 8 Bytes" << std::endl; // If Assert Passes it is aligned 8 bytes
}
Run Code Online (Sandbox Code Playgroud)
在这里演示
我使用std::size_t类型,因为这是您通常用于存储变量,对象等大小的类型.并且因为它std::size_t根据cppreference.com 扩展到表达式:
宏
offsetof扩展为类型的整数常量表达式std::size_t,其值是从指定类型的对象的开头到其指定成员的偏移量(以字节为单位),包括填充(如果有).