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);
}

Reply via email to