Can I count the of enum's fields at compile time?

Marc jckj33 at gmail.com
Thu Nov 23 02:02:51 UTC 2017


On Thursday, 23 November 2017 at 01:34:54 UTC, Ali Çehreli wrote:
> On 11/22/2017 05:21 PM, Marc wrote:
>> On Thursday, 23 November 2017 at 01:04:29 UTC, Jonathan M 
>> Davis wrote:
>>> On Thursday, November 23, 2017 00:58:21 Marc via 
>>> Digitalmars-d-learn wrote:
>>>> [...]
>>>
>>> import std.traits;
>>>
>>> enum countOfA = EnumMembers!A.length;
>>>
>>> - Jonathna M Davis
>> 
>> This sounds more readable. I was going to write a "function 
>> extension" to enum but I think it isn't really needed. Thank 
>> you too.
>
> As an eponymous template:
>
> enum One { a }
> enum Three { a, b, c }
>
> import std.range : EnumMembers;
> enum countOf(E) = EnumMembers!E.length;
>
> unittest {
>     static assert(countOf!One == 1);
>     static assert(countOf!Three == 3);
> }
>
> void main() {
> }
>
> Ali

whoa, this is so easy and elegant. I'm falling in love with D. 
Thank you too!


More information about the Digitalmars-d-learn mailing list