Workarounds for Lack of Mutable Keyword

Craig Black craigblack2 at cox.net
Thu Apr 3 02:22:33 PDT 2008


The second solution that I posted didn't work if the second parameter was 
const.  This solution will.  It uses a ForceCast template.  BTW, this 
template will work for more than just const.  Since D doesn't allow 
returning a reference, we must pass a pointer to ForceCast and dereference 
the result.

import std.stdio;

T ForceCast(T, S)(S a) { return *cast(T*)cast(int)(&a); }

class A
{
public:
  int x = 0;
  const void setX(const int nx) { *ForceCast!(int*)(&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