gpt4 book ai didi

c++ - 你能写一个静态断言来验证数据成员的偏移量吗?

转载 作者:可可西里 更新时间:2023-11-01 17:36:45 25 4
gpt4 key购买 nike

给定以下结构:

struct ExampleStruct {
char firstMember[8];
uint64_t secondMember;
};

有没有办法编写静态断言来验证 secondMember 的偏移量是 8 字节的某个倍数?

最佳答案

偏移量

可以使用cstddef 库自带的offsetof宏。在这里我首先得到偏移量,然后我使用 modulus operator检查它是否是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";
}

演示 here

Offsetofstatic_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
}

演示 here

类型用途

我使用 std::size_t 类型,因为这是您通常用来存储变量、对象等大小的类型。也因为它根据 cppreference.com 扩展为 std::size_t 表达式:

The macro offsetof expands to an integral constant expression of type std::size_t, the value of which is the offset, in bytes, from the beginning of an object of specified type to its specified member, including padding if any.

引用资料

cpprefrence

cplusplus

关于c++ - 你能写一个静态断言来验证数据成员的偏移量吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39907697/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com