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.

@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 T
{
    UNSET,
    QUERY,
    PRIVMSG,
    RPL_ENDOFMOTD
}

with (T)
{
    static assert(Enum!T.fromString("QUERY") == QUERY);
    static assert(Enum!T.fromString("PRIVMSG") == PRIVMSG);
    static assert(Enum!T.fromString("RPL_ENDOFMOTD") == RPL_ENDOFMOTD);
    static assert(Enum!T.fromString("UNSET") == UNSET);
    assertThrown!ConvException(Enum!T.fromString("DOESNTEXIST"));  // needs @system
}

with (T)
{
    static assert(Enum!T.toString(QUERY) == "QUERY");
    static assert(Enum!T.toString(PRIVMSG) == "PRIVMSG");
    static assert(Enum!T.toString(RPL_ENDOFMOTD) == "RPL_ENDOFMOTD");
}