Is there kind of "associative tuple" - like syntax in D?

Artur Skawina art.08.09 at gmail.com
Sat Feb 22 05:03:50 PST 2014


On 02/21/14 18:57, Uranuz wrote:
> In my template functions, classes it's necessary to write variadic template parameter list, where elements are options to this class/function  changing it's behaviour. But they are optional and may be not set at all. These options may be folowed by variadic template parameter list that will be processed in static foreach loop. What I'm thinking about is creating some sort of key-value tuple syntax like in associative arrays. For example I could set components or options of my template in easy-to-read manner.

You could wrap all the options in special types, as already suggested. If you don't
want to do that, and only need them to affect /local/ behavior, something like this
will work:

   class Foo(string OPTS, A...) {
      private static {
         auto _getOpts() {
            struct O {
               byte opt1;
               string opt2 = "def";
               bool b;
               string[string] extra;
            }
            struct ON { mixin("enum "~OPTS~";"); }
            O o;
            foreach (N; __traits(allMembers, ON))
               mixin("o. "~N~" = ON. "~N~";");
            return o;
         }
         enum opts = _getOpts();
         auto _getExtra(K)(K k) { if (auto p = k in opts.extra) return *p; return null; }
      }

      static if (opts.opt1>9)
         { /*...*/ pragma(msg, opts.opt1); }
      static if (opts.b && opts.opt2!="def")
         { /*...*/ pragma(msg, opts.opt2); }
      static if (_getExtra("b"))
         { /*...*/ pragma(msg, opts.extra["b"]); }

      /* handle 'A'... */
      /*...*/
   }

   void main() {
      alias MyFoo1 =
         Foo!q{opt1 = 42, opt2 = "blah", b = true, extra = ["a":"b", "b":"c"]};
         
      alias MyFoo2 = Foo!(q{b = false}, MyFoo1, 3.14, "etc");
   }


Not ideal, but right now I can't think of a simpler solution, using today's D.

artur


More information about the Digitalmars-d-learn mailing list