How can i get the value from an enum when passed to a function?
Jakob Ovrum
jakobovrum at gmail.com
Sun Jan 19 10:18:07 PST 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"
---
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
More information about the Digitalmars-d-learn
mailing list