c++ - 在编译时确定结构成员字节偏移量?

标签 c++ struct offset compile-time offsetof

我想在编译时找到结构成员的字节偏移量。例如:

struct vertex_t
{
    vec3_t position;
    vec3_t normal;
    vec2_t texcoord;
}

我想知道 normal 的字节偏移量是(在本例中它应该是 12。)

我知道我可以使用 offsetof,但这是一个运行时函数,我不想使用它。

我正在努力实现的目标是否可行?

编辑:offsetof 是编译时的,我的错!

最佳答案

offsetof 是一个编译时常量,如果我们看一下C++标准草案C.3 C标准库段落 2 说:

The C++ standard library provides 57 standard macros from the C library, as shown in Table 149.

并且该表包括offsetof。如果我们转到 C99 草案标准部分 7.17 Common definitions 段落 3 包括:

offsetof(type, member-designator)

which expands to an integer constant expression that has type size_t, the value of which is the offset in bytes [...]

关于c++ - 在编译时确定结构成员字节偏移量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19943194/

相关文章:

struct - IDL : Accessing struct fields using field names stored in variables?

c++ - 尝试访问数组时数据从数组中丢失

c++ - 如何使用多指针写入 ProcessMemory

mysql - 查询结果的偏移量

iOS Mapkit - 如何将用户的位置偏移指定量

python - sparse_hash_map 对于特定数据非常慢

c++ - 获取 IAMStreamConfig 接口(interface)失败

c++ - 将 MinGW64 库与 MSVC 2010 链接

c++ - 类(class)设计的选择

c# - 指向结构数组中项目的索引器不起作用