final switch on Algebraic

2015-03-29 Thread Freddy via Digitalmars-d-learn
Is there any way to do a final switch statement in std.variant's 
Algebraic.


Re: final switch on Algebraic

2015-03-29 Thread Meta via Digitalmars-d-learn

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"
}