Why doesn't std.variant.visit automatically call the provided delegates?

Adam D. Ruppe via Digitalmars-d digitalmars-d at puremagic.com
Sat Nov 5 03:09:55 PDT 2016


On Saturday, 5 November 2016 at 08:27:49 UTC, Nemanja Boric wrote:
>     // This - does nothing
>     variant.visit!(    (string s) => { enforce(false); x = 2; },

It calls the function... which returns a delegate, which you 
never called.

This is one of the most common mistakes people are making: {} in 
D is a delegate, and () => is a delegate, therefore () => {} is a 
delegate that returns a delegate... usually NOT what you want.

What you wrote is equivalent to writing

delegate() callback(string s) {
    return delegate() {
          enforce(false);
          x = 2;
    };
}


Do not use the => syntax if there is more than one expression. 
You'll get what you want by simply leaving the => out:

>
>     // This works as expected
>     variant.visit!(    (string s) { x = 2; },
>                        (int i)    { x = 3; });




More information about the Digitalmars-d mailing list