I have (re?)invented this approach to zero-cost properties with data member syntax. By this I mean that the user can write:
some_struct.some_member = var;
var = some_struct.some_member;
and these member accesses redirect to member functions with zero overhead.
While initial tests show that the approach does work in practice, I'm far from sure that it is free from undefined behaviour. Here's the simplified code that illustrates the approach:
template <class Owner, class Type, Type& (Owner::*accessor)()>
struct property {
operator Type&() {
Owner* optr = reinterpret_cast<Owner*>(this);
return (optr->*accessor)();
}
Type& operator= (const Type& t) {
Owner* optr = reinterpret_cast<Owner*>(this);
return (optr->*accessor)() = t;
}
};
union Point
{
int& get_x() { return xy[0]; }
int& get_y() { return xy[1]; }
std::array<int, 2> xy;
property<Point, int, &Point::get_x> x;
property<Point, int, &Point::get_y> y;
};
The test driver demonstrates that the approach works and it is indeed zero-cost (properties occupy no additional memory):
int main()
{
Point m;
m.x = 42;
m.y = -1;
std::cout << m.xy[0] << " " << m.xy[1] << "\n";
std::cout << sizeof(m) << " " << sizeof(m.x) << "\n";
}
Real code is a bit more complicated but the gist of the approach is here. It is based on using a union of real data (xy
in this example) and empty property objects. (Real data must be a standard layout class for this to work).
The union is needed because otherwise properties needlessly occupy memory, despite being empty.
Why do I think there's no UB here? The standard permits accessing the common initial sequence of standard-layout union members. Here, the common initial sequence is empty. Data members of x
and y
are not accessed at all, as there are no data members. My reading of the standard indicate that this is allowed. reinterpret_cast
should be OK because we are casting a union member to its containing union, and these are pointer-interconvertible.
Is this indeed allowed by the standard, or I'm missing some UB here?
std::launder
? – Larchunion
s, and after entrenching it in my program, discovered that it was UB for the same reason. That was a fun rewrite... (I mean, in totality, it was, because I ended up with code that was better and more flexible for other reasons - but I didn't like being rushed stressfully into it!) – Bakermanunion U { char a; char b; } u {}; reinterpret_cast<char*>(&u);
? – Larch