Created
January 4, 2021 15:32
-
-
Save PetarKirov/20bafbc9543f255854136dce475c7458 to your computer and use it in GitHub Desktop.
dlang - validate input matches enum member name
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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