Workarounds for Lack of Mutable Keyword

Craig Black craigblack2 at cox.net
Thu Apr 3 02:00:17 PDT 2008


The previous solution that I proposed only works because of a bug in DMD. 
See the "const/invariant bug" post for more info on the bug.  But I found 
another solution.  Const doesn't seem to cooperate well with templates, so

void ConstAssign(T)(ref const T a, T b) { *cast(T*)cast(int)(&a) = b; }

doesn't work but

void ConstAssign(T, S)(ref T a, S b) { *cast(S*)cast(int)(&a) = b; }

does work, as long as the second parameter not const.

Here's the full example:

import std.stdio;

void ConstAssign(T, S)(ref T a, S b) { *cast(S*)cast(int)(&a) = b; }

class A
{
public:
  int x = 0;
  const void setX(int nx) { ConstAssign(x, nx); }
}

void foo(const A a) { a.setX(1); }

int main(char[][] args)
{
  A a = new A;
  foo(a);
  writefln(a.x);
  return 0;
} 




More information about the Digitalmars-d mailing list