why won't byPair work with a const AA?
Matthew Gamble via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Sat Jul 29 22:15:11 PDT 2017
On Sunday, 30 July 2017 at 04:36:19 UTC, Ali Çehreli wrote:
> 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
Thanks Ali,
That works to solve the compile problem. Seems the data in aa was
safe from modification without the const or casting, even if the
values are reference types (i.e. ClassB[string]). Is that
expected?
Best,
Matt
More information about the Digitalmars-d-learn
mailing list