www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - How to do a checked cast from base-type to enum-type

reply "dnspies" <dspies ualberta.ca> writes:
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
}
Apr 05 2014
parent "Chris Nicholson-Sauls" <ibisbasenji gmail.com> writes:
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/phob s/std/conv.d(1854): Value (d) does not match any member value of enum 'E'
Apr 05 2014