Class Type Parameters

Jarrett Billingsley kb3ctd2 at yahoo.com
Thu Jan 24 06:05:40 PST 2008


"Hans-Eric Grönlund" <hasse42g at gmail.com> wrote in message 
news:fn9csm$109r$1 at digitalmars.com...
>> Also, this function would be a great place to use a lazy void parameter 
>> for
>> the toTry parameter ;)
>
> Pardon me for being ignorant, but could you elaborate a little on this 
> subject?
>
>

:D

void retryable(ClassInfo info, int times, lazy void totry)
{
    for(int i = 0; i < times; i++)
    {
        try
        {
            totry();
            break;
        }
        catch(Exception e)
        {
            if(_d_dynamic_cast(e, info))
                continue;
            else
                throw e;
        }
    }
}

Notice that the body of the function has not changed, we still call totry as 
a function.

Lazy parameters are sort of syntactic sugar.  You put "lazy T" on a 
parameter, it is implicitly a "T delegate()".  The magic happens when the 
function is actually called.  With the old version that took a delegate, we 
had to write:

retryable(typeid(Exception), 5, { connectToDB(); });

But lazy parameters allow us to use a normal-looking expression there:

retryable(typeid(Exception), 5, connectToDB());

The compiler sees that that's a lazy parameter and implicitly converts it to 
a delegate literal with that code in it.

If you want to have more code in the lazy parameter, it gets a bit tricky:

retryable(typeid(Exception), 5,
{
    func1();
    func2();
    func3();
}()); // <<< notice extra set of parens here!

The reason we have to have that extra set of parens is that the compiler 
will wrap this in another delegate literal, leaving us (internally) with 
something like:

void __temp1()
{
    {
        func1();
        func2();
        func3();
    }();
}

If we don't put the call at the end of the delegate literal, your lazy 
parameter just defines a function and does nothing else. 




More information about the Digitalmars-d-learn mailing list