Nothrow std.conv.to with explicit default value
Per Nordlöw
per.nordlow at gmail.com
Wed Jun 20 09:52:04 UTC 2018
On Wednesday, 20 June 2018 at 09:37:00 UTC, Per Nordlöw wrote:
> AFAICT, string-to-enum-conversion must include a switch
> containing a static foreach over all the enumerators, right?
My suggestion for nothrow @nogc string-to-enum conversion with
default value
T toDefaulted(T)(scope const(char)[] value,
T defaultValue) @safe pure nothrow @nogc
if (is(T == enum))
{
switch (value)
{
static foreach (index, member; __traits(allMembers, T))
{
case member:
return cast(T)(index);
}
default:
return defaultValue;
}
}
@safe pure nothrow /*TODO @nogc*/ unittest
{
enum E { unknown, x, y, z }
assert("x".toDefaulted!(E)(E.init) == E.x);
assert("_".toDefaulted!(E)(E.init) == E.unknown);
}
More information about the Digitalmars-d-learn
mailing list