Generic collection/element function signatures in D2 versus D1

Steven Schveighoffer schveiguy at yahoo.com
Tue Sep 7 07:33:11 PDT 2010


On Tue, 07 Sep 2010 09:28:18 -0400, Pelle <pelle.mansson at gmail.com> wrote:

> On 09/07/2010 03:15 PM, Steven Schveighoffer wrote:
>> On Tue, 07 Sep 2010 08:56:15 -0400, Jacob Carlborg <doob at me.com> wrote:
>>
>>> On 2010-09-07 14:49, Steven Schveighoffer wrote:
>>>> On Sun, 05 Sep 2010 09:40:59 -0400, BLS <windevguy at hotmail.de> wrote:
>>>>
>>>>> On 05/09/2010 02:16, Jonathan M Davis wrote:
>>>>>> void foo(T)(T[] collection, T elem)
>>>>>>> {
>>>>>>> // Blah, whatever
>>>>>>> }
>>>>>>>
>>>>>
>>>>> I am curious, how this will look and feel once inout is working ?
>>>>>
>>>>> inout void foo(T)(inout(T)[] collection, inout T elem)
>>>>> {
>>>>> // Blah, whatever}
>>>>> }
>>>>>
>>>>
>>>> inout void doesn't make any sense. You can't have a const void or
>>>> immutable void.
>>>>
>>>> Now, if foo is a member function, then inout applies to the "this"
>>>> pointer, but even then, you need a return type other than void for  
>>>> inout
>>>> to be used.
>>>>
>>>> -Steve
>>>
>>> inout is only used when you want to return the same constness
>>> (mutable, const, immutable) as you passed in to the function. If you
>>> don't want that, or don't want to return anything then const(T)[] is
>>> what you want. It will accept mutable, const and immutable.
>>
>> Yes, exactly. This is why inout functions cannot return void.
>>
>> -Steve
>
> Hmm.
>
> class C {
>      void foo(void delegate(inout(C)) f) inout {
>          f(this);
>      }
> }
>
> Am I missing something?

Yes, a valid return.  Your function should be:

void foo(void delegate(const(C) f) const

It helps to understand that inout/const/immutable has NOTHING to do with  
code generation, it only has to do with limiting what compiles.  For this  
reason, an inout function is compiled once, and works on all three  
constancies (4 if you have a nested inout function).  For the entire  
function any inout variable is treated as a non-changeable value, just  
like const.  Then when you return, it's converted at the call site back to  
the constancy with which it was called.  If the return value is void, then  
there's nothing to convert, and no reason to use inout over const.

I'll repeat -- there is no benefit to inout if you are not returning  
anything.

-Steve


More information about the Digitalmars-d-learn mailing list