Workarounds for Lack of Mutable Keyword
Craig Black
craigblack2 at cox.net
Wed Apr 2 22:28:16 PDT 2008
I did it and it was very easy. I didn't know you could cast away const so
easily in D. This works for const, but not invariant. Since we have the
ability to subvert const so easily, there should be no problem living
without mutable fields.
import std.stdio;
void ConstAssign(T)(ref const T x, T y) { *cast(T*)&x = y; }
class A
{
public:
int x;
int y;
void setY(int ny) const { ConstAssign(y, ny); }
}
void foo(const A a) { a.setY(2); }
int main(char[][] args)
{
A a = new A;
a.y = 1;
foo(a);
writefln(a.y);
return 0;
}
More information about the Digitalmars-d
mailing list