why won't byPair work with a const AA?
Steven Schveighoffer via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Tue Aug 1 07:04:18 PDT 2017
On 7/30/17 12:19 AM, Matthew Gamble wrote:
> I have a class member function from which I'm trying to return a sorted
> array of key, value tuples stored in an associative array as a private
> member. The member function should be able to be marked const to prevent
> the AA from being modified. I have reduced the problem to the simple
> case below which won't compile with DMD v2.072.2.
>
> import std.array;
> import std.algorithm;
>
> class A
> {
> this() { aa = ["a":1, "b" : 2, "c" : 3]; }
> auto pairs() @property const { return
> aa.byPair.array.sort().release; }
> private:
> int[string] aa;
> }
>
> If I remove const from the pairs function it compiles fine. I'm just not
> sure this is a behavior I want. Any help/recommendation would be
> appreciated.
byPair must store a pointer to the data in the AA. If you mark the AA
const, then it must store a const pointer to AA data.
However, because we don't have tail modifiers, you can't construct just
one range that would make this work. We would need many different
ranges, one for each flavor of mutability.
So you are stuck doing what Ali recommended -- cast away the const.
In this case, no harm comes if you don't cast back to const (since the
value of the AA is `int`), but in general this solution isn't valid if
the value type contains references.
-Steve
More information about the Digitalmars-d-learn
mailing list