digitalmars.D.learn - [TWiD] static foreach loop variable
- Nick Treleaven (11/11) May 28 2019 Hi,
- Adam D. Ruppe (28/39) May 28 2019 Yes, intended, but also incomplete. The idea there is to use the
- Nick Treleaven (1/1) May 28 2019 Ok, thanks for explaining. Nice idea.
Hi, Last week's TWiD had a tip that didn't make sense: http://dpldocs.info/this-week-in-d/Blog.Posted_2019_05_20.html#tip-of-the-week template Locals(int i) { alias Whatever = int; } static foreach(i; [1, 2, 3]) { Locals!i.Whatever; } The body is just `int;`. Not sure how to reach Adam. What was intended?
May 28 2019
On Tuesday, 28 May 2019 at 13:43:45 UTC, Nick Treleaven wrote:Hi, Last week's TWiD had a tip that didn't make sense: http://dpldocs.info/this-week-in-d/Blog.Posted_2019_05_20.html#tip-of-the-week template Locals(int i) { alias Whatever = int; } static foreach(i; [1, 2, 3]) { Locals!i.Whatever; }The body is just `int;`. Not sure how to reach Adam. What was intended?Yes, intended, but also incomplete. The idea there is to use the template as a namespace for whatever local stuff you had. (I adapted this from a reflection thing where Whatever would have been an alias to a member type, and then in simplifying to get to just the new idea - and in a rush to type it up that day - I removed like all the context). So it might actually be more like (still an incomplete example but more complete): void test(T)() { template Locals(int i) { static if(is(typeof(__traits(getMember, T, __traits(allMembers, T)[i])) Ret == return)) alias ReturnValue = Ret; } static foreach(idx, t; __traits(allMembers, T)) { mixin("auto " ~ t ~ "() { return Locals!idx.ReturnValue.init; }"); } } So now the Locals template wraps a bunch of aliases so we can refer to them more succinctly later. A regular alias defined inside that static foreach would end up being duplicated in future iterations. Putting the extra {} around it would mean the mixed in function would not be visible outside. so the Locals template is just a collection of convenience aliases in a namespace.
May 28 2019