initializing const maps with value types having aliasing
Jonathan M Davis
jmdavisProg at gmx.com
Wed Mar 20 12:01:17 PDT 2013
On Wednesday, March 20, 2013 19:41:00 Dan wrote:
> The following works and is the only way I have found to
> initialize m.
> Unfortunately it requires the cast.
>
> Is this safe to do?
> Is there a better way?
> Is this a bug or are future features coming to clean it up?
>
> Thanks
> Dan
>
> ----------------------------------
> import std.stdio;
> struct S {
> this(this) { x = x.dup; }
> char[] x;
> }
>
> const(S[string]) m;
> static this() {
> // Is there a cleaner way?
> cast(S[string])m = [ "foo" : S(['a']) ];
> }
>
> void main() {
> writeln(m["foo"]);
> }
Why are you casting? The cast shouldn't be necessary, because you're doing the
initialization inside a static constructor. If you had problems, I'd expect it
to be that AAs don't work properly when const (I know that there are issues
when they're immutable) or that you can't insert elements into a const or
immutable AA (which you'll never be able to do). But what you're doing here
should work just fine without the cast. Assuming that AAs worked with const or
immutable correctly, then it would be normal to do something like
immutable int[string] aa;
static this()
{
int[string] temp;
temp["foo"] = 7;
temp["blah"] = 12;
aa = assumeUnique(temp);
}
- Jonathan M Davis
More information about the Digitalmars-d-learn
mailing list