How to search for an enum by values and why enum items aren't unique
stunaep via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Wed Jul 27 08:42:43 PDT 2016
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. 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.
More information about the Digitalmars-d-learn
mailing list