www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - How can i get the value from an enum when passed to a function?

reply "Gary Willoughby" <dev nomad.so> writes:
How can i get the value from an enum when passed to a function? 
For example i have the following code:

import std.stdio;

enum E : string
{
	one = "1",
	two = "2",
}

void print(E e)
{
	writefln("%s", e);
}

void main(string[] args)
{
	print(E.one);
}

The output is 'one'. How can i get at the value '1' instead. I 
could change the print function to accept a string like this:

void print(string e)
{
	writefln("%s", e);
}

but i lose the constraint of using an enum for the values.
Jan 19 2014
parent reply "Tobias Pankrath" <tobias pankrath.net> writes:
On Sunday, 19 January 2014 at 17:37:54 UTC, Gary Willoughby wrote:
 How can i get the value from an enum when passed to a function? 
 For example i have the following code:

 import std.stdio;

 enum E : string
 {
 	one = "1",
 	two = "2",
 }

 void print(E e)
 {
 	writefln("%s", e);
 }

 void main(string[] args)
 {
 	print(E.one);
 }

 The output is 'one'. How can i get at the value '1' instead. I 
 could change the print function to accept a string like this:

 void print(string e)
 {
 	writefln("%s", e);
 }

 but i lose the constraint of using an enum for the values.
You'll need to cast the value, but you can guard this cast using std.traits.OriginalType or write a toOType function. auto toOType(E)(E e) if(is(E == enum)) { return cast(OriginalType!E) e; } I never get these is-expressions right on first try, but the idea should be clear.
Jan 19 2014
parent "Jakob Ovrum" <jakobovrum gmail.com> writes:
On Sunday, 19 January 2014 at 18:07:46 UTC, Tobias Pankrath wrote:
 You'll need to cast the value, but you can guard this cast 
 using std.traits.OriginalType or write a toOType function.

 auto toOType(E)(E e) if(is(E == enum)) { return 
 cast(OriginalType!E) e; }

 I never get these is-expressions right on first try, but the 
 idea should be clear.
You don't have to use an explicit cast. Enum values can be implicitly converted to their base enum type: --- string str = E.one; writeln(str); // prints "1" --- If DMD pull request #1356[1] is pulled, I think we'll be able to do: --- writeln(string(E.one)); // prints "1" --- I recommend avoiding the cast operator whenever possible. [1] https://github.com/D-Programming-Language/dmd/pull/1356
Jan 19 2014