April 06, 2014
Is there a way to do a checked cast from a base type to an enum-type (so that an exception is thrown if it fails)?

ie something like

enum x : dchar { A : 'a', B : 'b', C : 'c' };

x get_x() {
 dchar r = get_char();
 return cast(x)r; //Throw exception if this cast fails
}
April 06, 2014
On Sunday, 6 April 2014 at 02:21:35 UTC, dnspies wrote:
> Is there a way to do a checked cast from a base type to an enum-type (so that an exception is thrown if it fails)?
>
> ie something like
>
> enum x : dchar { A : 'a', B : 'b', C : 'c' };
>
> x get_x() {
>  dchar r = get_char();
>  return cast(x)r; //Throw exception if this cast fails
> }


enum E : dchar {
    A = 'a',
    B = 'b',
    C = 'c'
}

void main () {
    import std.conv;
    dchar c = 'd';
    E e = to!E( c );
}


std.conv.ConvException@/home/grant/.dvm/compilers/dmd-2.064.2/bin/../src/phobos/std/conv.d(1854): Value (d) does not match any member value of enum 'E'