I'm searching a way to get the offset of a member variable to statically pass this offset to the member variable. Basically I want achieve this:
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;
}
Is there a way to do this?
First of, as requested, you're goal is not achievable as the type of a
impacts the offst of a
inside B
:
struct B
{
int some_variables[256];
A</* offset of a inside B */> a;
};
This is alignment.
You could use the standard macro offsetof
. This implies two things:
offsetof(type, member)
is well-defined only for standard-layout type
s, the enclosing type must be standard-layout,offsetof
can only be "called" on complete types, its statically-computed result can only be set to the subobject dynamically; it canoot be a template non-type parameter, but can be a constructor argument.#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
But as you commented, this is quite useless as Location
could be simply defined as
template<class T>
struct Location
{
Location(T* location) : location_(location) {}
T* location_;
operator T* () const { return location; }
};
and initialized with Location location = this;
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With