Nothrow std.conv.to with explicit default value
Per Nordlöw
per.nordlow at gmail.com
Wed Jun 20 14:39:48 UTC 2018
On Wednesday, 20 June 2018 at 09:54:29 UTC, Per Nordlöw wrote:
>> 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);
>> }
>
> Oops, this doesn't work for enums with "holes". How do I most
> easily fix that?
This is my solution:
T toDefaulted(T)(scope const(char)[] value, T defaultValue) @safe
pure nothrow @nogc
if (is(T == enum))
{
switch (value)
{
static foreach (member; __traits(allMembers, T))
{
case member:
mixin(`return T.` ~ member ~ `;`);
}
default:
return defaultValue;
}
}
Is there a way to avoid compile-time-string-concat plus mixin
here?
More information about the Digitalmars-d-learn
mailing list