On 08/11/2012 03:48 PM, ReneSac wrote:
> On Tuesday, 24 July 2012 at 05:30:49 UTC, Ali Çehreli wrote:

>> - Use an out parameter, which can have a default lvalue:
>>
>> int g_default_param;
>>
>> void foo(ref int i = g_default_param)
>> {
>> if (&i == &g_param) {
>> // The caller is not interested in 'i'
>>
>> } else {
>> // The caller wants 'i'
>> i = 42;
>> }
>> }
>>
>> void main()
>> {
>> foo();
>>
>> int i;
>> foo(i);
>> assert(i == 42);
>> }
>
> This is not working inside a class. I'm not sure what default value I
> should put when I don't know the type entered:
>
> class a (T) {
> T dummy = T.init;
> bool foo(int a, out T optional = dummy)
> {
> return true;
> }
> }
>
> void main () {
> auto c = new a!uint();
> c.foo(5);
> }
>
> I get the following error:
>
> Error: need 'this' to access member dummy
>

I am not a fan of this solution either. To make the code to compile, define dummy as static:

    static T dummy = T.init;  // <-- this works

That way there will be just one copy for the entire type, instead of one copy per object.

I also tried to define it as immutable but the following line fails to compile:

    static immutable T dummy = T.init;  // <-- compilation error

I thought that a solution would be to define 'static this()':

class a (T){
    static immutable T dummy;

    static this()
    {
        dummy = T.init;
    }

    bool foo(int a, out T optional = dummy)
    {             // <-- compilation error on this line
        return true;
    }
}

Still fails to compile:

  Error: cast(uint)dummy is not an lvalue

The error is on the line that I have pointed in the code. I think this is a compiler bug. T is not a reference type and 'cast(uint)dummy' not being an lvalue should not matter.

I tried an enum too but a different error on the same line:

    static enum T dummy = T.init;

  Error: constant 0u is not an lvalue

Ali

Reply via email to