Skip to content

Instantly share code, notes, and snippets.

@PetarKirov
Created January 4, 2021 15:32
Show Gist options
  • Save PetarKirov/20bafbc9543f255854136dce475c7458 to your computer and use it in GitHub Desktop.
Save PetarKirov/20bafbc9543f255854136dce475c7458 to your computer and use it in GitHub Desktop.
dlang - validate input matches enum member name
void main()
{
static immutable pairs = [__traits(allMembers, Pair)];
pragma (msg, pairs); // ["EURUSD", "GBPUSD", "USDCHF", "XAUUSD"]
import std.stdio : writeln;
"EURUSD".parseEnum!Pair.writeln;
"GBPUSD".parseEnum!Pair.writeln;
"USDCHF".parseEnum!Pair.writeln;
"XAUUSD".parseEnum!Pair.writeln;
"asd".parseEnum!Pair.writeln;
}
enum Pair
{
EURUSD,
GBPUSD,
USDCHF,
XAUUSD,
}
E parseEnum(E)(string input)
if (is(E == enum))
{
switch (input)
{
static foreach (member; __traits(allMembers, E))
case member:
return mixin("E.", member);
default:
// Replace with whatever other error-handling mechanism you want:
throw new Exception("Can't parse enum `" ~ E.stringof ~ q"{` - input: "}" ~ input ~ `".`);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment