why won't byPair work with a const AA?

Steven Schveighoffer via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Wed Aug 2 10:15:44 PDT 2017


On 8/2/17 11:52 AM, H. S. Teoh via Digitalmars-d-learn wrote:
> On Wed, Aug 02, 2017 at 08:20:23AM -0400, Steven Schveighoffer via Digitalmars-d-learn wrote:
>> On 8/1/17 7:44 PM, H. S. Teoh via Digitalmars-d-learn wrote:
> [...]
>> You can iterate a const AA, but if you want to iterate a non-const AA,
>> you need a different type.
>>
>> For instance, if your AA is int*[string], you will get const(int*) out
>> of it, which may not be what you want.
>>
>> Unless your range is a slice or a pointer, then you can't do it
>> properly without having separate types for const, immutable, mutable
>> ranges. You can use templates to build them, but it's not
>> straightforward or pleasant.
> [...]
> 
> Hmm. This seems like a perfect use case for inout, though I'm not
> confident the current implementation of inout can handle this. You'd do
> something like this:
> 
> 	auto byPair(AA)(inout(AA) aa)
> 	{
> 		struct Result
> 		{
> 			inout(Slot)* current;
> 			... // range primitives here
> 		}
> 		return Result(aa);
> 	}
> 
> What I'm unsure of is whether the current implementation of inout can
> handle the inout inside the definition of Result.

It's not currently legal, you can't have inout members of a struct. This 
could be added, but it still wouldn't work, because you can't "strip 
off" the inout part upon return.

The real answer is to have tail modifiers for structs, so you can do the 
same thing an array does. Note that if Result is an array, you CAN use 
inout:

auto byPair(AA)(inout(AA) aa)
{
    alias Result = inout(X)[];
    return Result(...);
}

-Steve


More information about the Digitalmars-d-learn mailing list