Pure delegate not quite pure?

Steven Schveighoffer via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Wed Jul 1 05:34:35 PDT 2015


On 6/30/15 9:29 PM, Tofu Ninja wrote:
> On Wednesday, 1 July 2015 at 00:13:36 UTC, Jesse Phillips wrote:
>> On Tuesday, 30 June 2015 at 22:23:40 UTC, Tofu Ninja wrote:
>>> On Tuesday, 30 June 2015 at 22:05:43 UTC, Steven Schveighoffer wrote:
>>>> Have you tried placing const on the function signature? i.e.:
>>>>
>>>> pure int delegate() const d = () const {...
>>>>
>>>> That's how you'd do it (I think, didn't test) if the delegate
>>>> context pointer was a class/struct.
>>>>
>>>
>>> Nah, says its only available for non-static member functions.
>>
>> hmm, it seems that this would be an appropriate enhancement. It
>> doesn't make sense on a function, but as it relates to delegates I'd
>> say it makes sense to allow const to be added.
>
> const, immutable, shared, inout. Not sure if they all make sense on
> delegates, but those are the options for member functions, so they might
> apply to delegates as well.

immutable is probably incorrect without a cast, since immutable cannot 
be applied implicitly to non-immutable data, and if the data is all 
immutable already, no sense in tagging it immutable.

I really see use in allowing const.

inout is sketchy, I'm trying to think of how this applies, since inout 
is really for data types that are varied in their constancy. A function 
has only one addressable instance.

shared, well... I don't think we need it. Function stacks shouldn't be 
shared.

One thing you CAN do as a workaround, is put all your data to return 
into a static struct, and return delegates that address your data:

auto foo()
{
     static struct Storage
     {
         int x = 4;
         pure int dg() immutable { return x * x;} // should be strong-pure
     }
     immutable(Storage) s;
     auto d = &s.dg; // I *think* this allocates a closure, but if not, 
that's a bug.
     writeln(d());
     // s.x = 5; // invalid
     return d;
}

Really, a delegate on a function stack is like a single-instance 
private-defined struct like written above.

-Steve


More information about the Digitalmars-d-learn mailing list