DIP 1010--Static foreach--Formal Review

Steven Schveighoffer via Digitalmars-d digitalmars-d at puremagic.com
Tue Jul 11 07:23:27 PDT 2017


On 7/11/17 10:08 AM, jmh530 wrote:
> On Tuesday, 11 July 2017 at 07:42:22 UTC, Timon Gehr wrote:
>>
>> Yes, this code works and does what you want. (The difference to inout 
>> is that you actually get three different implementations and you are 
>> able to vary the implementation based on T.)
> 
> Clearly, this has more power than inout.

It's not as good actually. In the mutable form, you can modify the data.

It all depends on if you care about const guarantees or bloat. If you 
don't and just want to handle all forms, you can use a template (much 
easier IMO than using static foreach).

> I suppose what I'm wondering if it makes inout superfluous.

I would say no, inout has a very well defined and convenient mechanism 
to deal with properties on all const flavors of objects. There are many 
who say templates are good enough, so YMMV. However, nothing so far has 
successfully implemented the requirement that during the inout function 
execution, the compiler enforces no mutability.

> The other major use of inout is something like
> 
> class Foo
> {
>      void bar(int t) inout

hm..., this should probably return inout for it to make sense.

>      {
>      }
> }
> 
> which I imagine could be replaced now with SetFunctionAttributes, though 
> my method was a little ugly and I don't know if there's a more elegant 
> approach with static foreach.

There is a way to do it with 'this' template parameter:

int * member;
auto bar(this T)()
{
    return member; // returns const, immutable, or mutable depending on 
modifier for 'this'
}

Still is bloated into multiple instantiations, and still allowed to 
mutate for mutable call. Plus it's confusing.

-Steve


More information about the Digitalmars-d mailing list