static foreach considered

Artur Skawina via Digitalmars-d digitalmars-d at puremagic.com
Mon Jun 8 16:00:45 PDT 2015


On 06/08/15 22:02, Andrei Alexandrescu via Digitalmars-d wrote:
> Walter and I are looking at ways to implement it. Here's a baseline without static foreach - a "trace" function that prints function calls before they are made:
> 
> http://dpaste.dzfl.pl/762c83c7fe30
> 
> If the function is overloaded, that won't work. In such cases, static foreach might be helpful. Here's code from the cycle "I have a dream":
> 
> http://dpaste.dzfl.pl/82a70c809210

The goal should be more like:

   template trace(alias fun) {
      static foreach (O; Overloads!fun)
         auto ref trace(Parameters!O args) {
              write("Tracing: ", __traits(identifier, fun), "(");
              foreach (i, arg; args) {
                  if (i) write(", ");
                  write(arg);
              }
              writeln(")");
              return fun(args);
         }
   }

And, btw, one of your asserts in that dreamy example has an
off-by-one bug. Of course the only reason I spotted it is because
I actually ran the code. ;) [1]

artur

[1] My old static-foreach hack makes it look like this:

  template trace(alias fun) {
      alias OS = Overloads!fun;
      #foreach (I, _; OS) {
         auto ref trace(Parameters!(OS[$I]) args) {
              write("Tracing: ", __traits(identifier, fun), "(");
              foreach (i, arg; args) {
                  if (i) write(", ");
                  write(arg);
              }
              writeln(")");
              return fun(args);
         }
      }
   }

which obviously isn't that pretty, but has the advantage of working right
now. But w/o a built-in implementation it (a) is a bit too verbose, and
(b) doesn't nest very well; a built-in version wouldn't have these problems.


More information about the Digitalmars-d mailing list