c++ - 静态获取成员变量的偏移量

标签 c++ templates

我正在寻找一种方法来获取成员变量的偏移量,以将此偏移量静态传递给成员变量。基本上我想实现这个:

template <std::intptr_t OFFSET>
struct A
{
    std::intptr_t self()
    {
        return reinterpret_cast<std::intptr_t>(this) - OFFSET;
    }
};
struct B
{
    int some_variables[256];
    A<???> a;
};
int main()
{
    B b;
    assert(reinterpret_cast<std::intptr_t>(&b) == b.a.self()); // shall pass
    return 0;
}

有办法吗?

最佳答案

首先,根据要求,您的目标无法实现,因为 a 的类型会影响 Ba 的偏移量:

struct B
{
    int some_variables[256];
    A</* offset of a inside B */> a;
};

这是 alignment .


您可以使用标准宏 offsetof .这意味着两件事:

  1. 因为 offsetof(type, member) 仅针对 standard-layout 定义明确type,封闭类型必须是标准布局,
  2. 并且由于offsetof只能在完整类型上“调用”,其静态计算结果只能动态设置到子对象;它不能是模板非类型参数,但可以是构造函数参数。

完整程序

#include <cassert>
#include <cstdint>
#include <cstddef>

struct Location
{
    Location(std::size_t offset) : offset_(offset) {}
    std::size_t offset_;
    operator std::intptr_t () const { return reinterpret_cast<std::intptr_t>(this) - offset_; }
};

struct SomeType
{
    int some_variables[256];
    Location location = offsetof(SomeType, location);
};

int main()
{
    SomeType obj;
    assert(reinterpret_cast<std::intptr_t>(&obj) == obj.location); // does pass
}

live demo

但是正如您评论的那样,这毫无用处,因为 Location 可以简单地定义为

template<class T>
struct Location
{
    Location(T* location) : location_(location) {}
    T* location_;
    operator T* () const { return location; }
};

并使用 Location location = this; 进行初始化。

关于c++ - 静态获取成员变量的偏移量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54747219/

相关文章:

c++ - 使用 boost multi_index_container 来保留插入顺序

c++ - Boost program_options将多个配置文件解析结果存储到一个parsed_options中

c++ - 'deep' 模板参数推导是否可行?

c++ - 返回模板类型的模板函数

c++ - 内存使用问题

c++ - 类模板特化优先级/歧义

c++ - C++中的特殊枚举

c++ - 使用不同优化级别编译的不同翻译单元中的模板实例化

Java 扩展泛型类型参数

c++ - SFINAE 和 std::numeric_limits