xxxxxxxxxx
struct HeadConstable(T) {
import std.traits : ReturnType;
ReturnType!makeAccessor accessor;
private static makeAccessor(return ref T v) {
ref T impl() {
return v;
}
return &impl;
}
this(return ref T v) const {
accessor = makeAccessor(v);
}
ref T get() const pure {
return accessor();
}
void opAssign(Q)(Q rhs) const
if (__traits(compiles, { get() = rhs; })) {
get() = rhs;
}
}
auto headConst(T)(ref T v) {
return const HeadConstable!T(v);
}
void main() pure
{
int x;
auto y = headConst(x);
version (TestConstness) {
int z;
y = headConst(z); // Error: cannot modify const expression y
}
x = 1;
y = 2;
assert(x == 2);
}