How to search for an enum by values and why enum items aren't unique
Ali Çehreli via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Wed Jul 27 10:41:32 PDT 2016
On 07/27/2016 08:42 AM, stunaep wrote:
> On Wednesday, 27 July 2016 at 15:32:59 UTC, Meta wrote:
>> On Wednesday, 27 July 2016 at 13:59:54 UTC, stunaep wrote:
>>> So how would I make a function that takes an enum and an id as a
>>> parameter and returns a member in the enum? I tried for quite some
>>> time to do this but it wont let me pass Test as a parameter unless I
>>> use templates. I finally came up with this but it wont let me return
>>> null when there's nothing found
>>>
>>>> E findEnumMember(E)(int id) if (is(E == enum)) {
>>>> auto found = [EnumMembers!E].find!(a => a.id == id)();
>>>> if(!found.empty)
>>>> return found.front;
>>>> else
>>>> ...What do I return? null gives error
>>>> }
>>
>> If you're going to do it like this your only real options are to
>> return a Nullable!E or throw an exception if the id isn't found.
>
> I tried Nullable!E earlier and it didnt work.
import std.traits;
import std.algorithm;
import std.array;
import std.typecons;
Nullable!E findEnumMember(E)(int id) if (is(E == enum)) {
auto found = [EnumMembers!E].find!(a => a.id == id)();
if(!found.empty)
return Nullable!E(found.front);
else
return Nullable!E();
}
struct S {
int id;
}
enum MyEnum : S {
x = S(42),
invalid = S() // Useful for the other alternative
}
void main() {
auto a = findEnumMember!MyEnum(42);
assert(!a.isNull);
auto b = findEnumMember!MyEnum(7);
assert(b.isNull);
}
> I dont need it to be done
> like this, it just has to be done someway. I'm asking for help because
> that's the only way I could think of.
Another alternative is to require that the enum has a special sentinel:
else
return E.invalid;
Ali
More information about the Digitalmars-d-learn
mailing list