why won't byPair work with a const AA?

Steven Schveighoffer via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Aug 1 16:09:45 PDT 2017


On 8/1/17 6:50 PM, H. S. Teoh via Digitalmars-d-learn wrote:
> On Tue, Aug 01, 2017 at 10:04:18AM -0400, Steven Schveighoffer via Digitalmars-d-learn wrote:
>> On 7/30/17 12:19 AM, Matthew Gamble wrote:
> [...]
>>> 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.
> [...]
> 
> Actually, there's nothing about the implementation of both byKeyValue
> (the underlying implementation in druntime) and byPair in std.array that
> would preclude them from being used with const AA's.  The only flaw is
> that the declaration of byPair doesn't match const AA's:
> 
> 	https://issues.dlang.org/show_bug.cgi?id=17711
> 
> Here's the fix:
> 
> 	https://github.com/dlang/phobos/pull/5668

It works, because the byKeyValue implementation is so... ugly.

For instance this:

return Result(_aaRange(cast(void*)aa));

Just throws away all const/mutability. However, the Pair struct inside 
restores the correct modifiers. I hope...

If this were a true implementation without the opaqueness, it would not 
work properly.

-Steve


More information about the Digitalmars-d-learn mailing list