digitalmars.D.learn - template with enum arg ?
- chmike (17/17) Jun 08 2016 In a first implementation I defined a named enum in my class
- =?UTF-8?Q?Ali_=c3=87ehreli?= (28/45) Jun 08 2016 One way is to bring the enum values to the class scope:
- chmike (2/2) Jun 09 2016 This is awesome! I added it to my D cookbook.
In a first implementation I defined a named enum in my class which I could use with my template function foo. ---- final class Info { ... enum Value { info_1 = 1, ... } ... static bar(Value e) {...} } void foo(T)(T.Value e) { T.bar(e); } ---- I could then write : foo(Info.Value.info_1); I would prefer to write : foo(Info.info_1); If I change the enum into an anonymous enum the template doesn't work anymore. How could I solve this ? Also, do I need a template argument filter if() ?
Jun 08 2016
On 06/08/2016 10:02 AM, chmike wrote:In a first implementation I defined a named enum in my class which I could use with my template function foo. ---- final class Info { ... enum Value { info_1 = 1, ... } ... static bar(Value e) {...} } void foo(T)(T.Value e) { T.bar(e); } ---- I could then write : foo(Info.Value.info_1); I would prefer to write : foo(Info.info_1); If I change the enum into an anonymous enum the template doesn't work anymore. How could I solve this ? Also, do I need a template argument filter if() ?One way is to bring the enum values to the class scope: alias info_1 = Value.info_1; Which can be automated with a mixin: string expandEnumMembers(E)() { string result; foreach (m; __traits(allMembers, E)) { import std.string : format; result ~= format("alias %s = %s.%s;", m, E.stringof, m); } return result; } final class Info { enum Value { info_1 = 1, info_2 } mixin (expandEnumMembers!Value()); static bar(Value e) {} } void foo(T)(T.Value e) { T.bar(e); } void main() { foo(Info.info_1); foo(Info.info_2); } To see at compile time what is being mixed in, insert the following somewhere in your code: pragma(msg, expandEnumMembers!(Info.Value)); Ali
Jun 08 2016
This is awesome! I added it to my D cookbook. Thank you very much.
Jun 09 2016