digitalmars.D.learn - How can i get the value from an enum when passed to a function?
- Gary Willoughby (23/23) Jan 19 2014 How can i get the value from an enum when passed to a function?
- Tobias Pankrath (7/30) Jan 19 2014 You'll need to cast the value, but you can guard this cast using
- Jakob Ovrum (14/20) Jan 19 2014 You don't have to use an explicit cast. Enum values can be
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
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
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" --- 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