Enum

Template housing optimised functions to get the string name of an enum member, or the enum member of a name string.

std.conv.to is typically the go-to for this job; however it quickly bloats the binary and is not performant on larger enums.

Limitations: Does not work with enums whose members' values cannot be used in a switch statement. This includes enums with members that share values with other members, as well as enums of values that are non-string arrays or other complex types.

@safe
template Enum (
E
) if (
is(E == enum)
) {}

Members

Functions

fromString
E fromString(string enumstring)

Takes the member of an enum by string and returns that enum member.

toString
string toString(E value)

The inverse of fromString, this function takes an enum member value and returns its string identifier.

Parameters

E

enum to base this template on.

Examples

import std.conv : ConvException;
import std.exception  : assertThrown;

{
    enum E { a, b, c }

    static assert(Enum!E.fromString("a") == E.a);
    static assert(Enum!E.fromString("b") == E.b);
    static assert(Enum!E.fromString("c") == E.c);
    assertThrown!ConvException(Enum!E.fromString("d"));  // needs @system

    static assert(Enum!E.toString(E.a) == "a");
    static assert(Enum!E.toString(E.b) == "b");
    static assert(Enum!E.toString(E.c) == "c");
    static assert(Enum!E.toString(cast(E)1234) == "cast(E)1234");
}
{
    enum E
    {
        abc = "abc",
        def = "def",
        ghi = "ghi",
    }

    static assert(Enum!E.fromString("abc") == E.abc);
    static assert(Enum!E.fromString("def") == E.def);
    static assert(Enum!E.fromString("ghi") == E.ghi);
    assertThrown!ConvException(Enum!E.fromString("jkl"));  // as above

    static assert(Enum!E.toString(E.abc) == "abc");
    static assert(Enum!E.toString(E.def) == "def");
    static assert(Enum!E.toString(E.ghi) == "ghi");
    static assert(Enum!E.toString(cast(E)"jkl") == "cast(E)\"jkl\"");
}