top | item 44845553

(no title)

diegocg | 6 months ago

As someone who uses D and has been doing things like what you see in the post for a long time, I wonder why other languages would put attention to these tricks and steal them when they have been completely ignoring them forever when done in D. Perhaps Zig will make these features more popular, but I'm skeptic.

discuss

order

brabel|6 months ago

I was trying to implement this trick in D using basic enum, but couldn't find a solution that works at compile-time, like in Zig. Could you show how to do that?

Snarwin|6 months ago

  import std.meta: AliasSeq;

  enum E { a, b, c }

  void handle(E e)
  {
      // Need label to break out of 'static foreach'
      Lswitch: final switch (e)
      {
          static foreach (ab; AliasSeq!(E.a, E.b))
          {
              case ab:
                  handleAB();
                  // No comptime switch in D
                  static if (ab == E.a)
                      handleA();
                  else static if (ab == E.b)
                      handleB();
                  else
                      static assert(false, "unreachable");
                  break Lswitch;
          }
          case E.c:
              handleC();
              break;
      }
  }