This thread is a followup of
https://forum.dlang.org/post/vuljzyufphsywzevu...@forum.dlang.org
with a refocused subject and question.
I'm looking for a mutable reference to a none mutable object to
implement the flyweight pattern. It is for a library and its user
interface. So I'm not looking for hacks to get around the problem.
Here is a toy example showing what I try to achieve and that
fails to compile.
The main shows what I expect users should be able to do.
The aim is to allow the user to define another sets of constants
of base type Info in his own class (e.g. MyInfos) and with a
different implementation that the one provided in the example
class Infos.
----
import std.stdio;
import std.typecons;
interface Info { }
class Infos {
static class Obj : Info
{
this(string msg) immutable { this.msg = msg; }
private string msg;
string toString() immutable { return msg; }
}
static immutable one = new immutable Obj("I'm one");
}
void main()
{
Rebindable!Info x1, x2 = Infos.one;
assert(x1 is null);
assert(x1 == null);
assert(x2 !is null);
assert(x2 != null);
assert(x2 is Infos.one);
assert(x2 == Infos.one);
x1 = x2;
assert(x1 is x2);
assert(x1 == x2);
assert(x1 is Infos.one);
assert(x1 == Infos.one);
writeln(x1);
switch(x1)
{
case Infos.one: writeln("case Infos.one"); break;
default: writeln("default"); break;
}
// That is enough for today
}
----
Compiling this code with dmd
$ dmd --version
DMD64 D Compiler v2.071.0
Copyright (c) 1999-2015 by Digital Mars written by Walter Bright
I get the following errors:
$ dub build
Performing "debug" build using dmd for x86_64.
testrebindable ~master: building configuration "application"...
source/app.d(23,27): Error: cannot implicitly convert expression
(one) of type immutable(Obj) to app.Info
source/app.d(26,12): Error: use 'is' instead of '==' when
comparing with null
source/app.d(29,12): Error: use '!is' instead of '!=' when
comparing with null
source/app.d(43,5): Error: 'x1' must be of integral or string
type, it is a app.Info
source/app.d(45,10): Error: cannot implicitly convert expression
(one) of type immutable(Obj) to app.Info
dmd failed with exit code 1.