www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - deducing function/delegate in template method

reply =?UTF-8?B?Ikx1w61z?= Marques" <luismarques gmail.com> writes:
In this code:

    // accepts a list of handlers, for the respective types
     void addHandlers(T...)(T handlers)
     {
         foreach(handler; handlers)
         {
             addHandler(handler);
         }
     }

     // accepts one handler, for type T
     void addHandler(T)(void delegate (T) handler)
     {
         ...
     }

     ...

     foo.addHandler((int x) { /* always deduced as delegate */ });
     foo.addHandlers(delegate (int x) { /* if no scope access 
deduction fails */ });

If I call addHandler with a function/delegate literal then DMD 
deduces that the literal has to be a delegate, but if I call 
addHandlers then I have to explicitly mark my function/delegate 
literal as a delegate, otherwise the template match will fail if 
the function/delegate literal does not access something from its 
scope. Couldn't DMD also deduce this correctly in this case?

Also, how can I change addHandler to accept delegates with 
heterogeneous varargs? Something like:

     void addHandler(T...)(void delegate (T...) handler);

so that I can do:

     foo.addHandler((int x, float y) { });
May 24 2013
parent =?UTF-8?B?Ikx1w61z?= Marques" <luismarques gmail.com> writes:
On Friday, 24 May 2013 at 22:37:49 UTC, Luís Marques wrote:
     foo.addHandlers(delegate (int x) { /* if no scope access 
 deduction fails */ });
(I meant that deduction would fail if the literal was not marked as a delegate)
May 24 2013