final switch on Algebraic

Meta via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sun Mar 29 19:08:40 PDT 2015


On Sunday, 29 March 2015 at 23:19:31 UTC, Freddy wrote:
> Is there any way to do a final switch statement in 
> std.variant's Algebraic.

Not currently. However, std.variant.visit is probably what you 
want. It enforces that you handle all types contained in the 
Algebraic.

import std.variant;
import std.stdio;

//For convenience as typeof(null) has no name
alias Null = typeof(null);

alias Maybe(T) = Algebraic!(T, Null);

void main()
{
     Maybe!int n = 0;
     writeln(n); //Prints "0"

     n = null;
     writeln(n); //Prints "null"

     //Prints "I'm Null!"
     n.visit!(
         (int  i) => writeln("I'm an int!"),
         (Null n) => writeln("I'm Null!"),
     );

     auto m = n.visit!(
         (int  i) =>  i,
         (Null n) => -1,
     );
     writeln(m); //Prints "-1"
}


More information about the Digitalmars-d-learn mailing list