why won't byPair work with a const AA?

Ali Çehreli via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Jul 29 21:36:19 PDT 2017


On 07/29/2017 09:19 PM, 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.

I think it should work. I think a cast to unqualified is a safe 
workaround in this case:

     auto pairs() @property const { return 
(cast(int[string])aa).byPair.array.sort().release; }

Ali



More information about the Digitalmars-d-learn mailing list