downs wrote:
Alex wrote:
Is it possible, using templates, tuples, or some other mechanism, to implement 
named variadic arguments in D?

For example, I'd like to be able to do something like...
foo( 2, &bar, age : 10, status : "down");

and so forth.

Yes, with a small hack.

typedef int age_type;

age_type age(int i) { return cast(age_type) i; }

void foo(T...)(int i, Bar*, T t) {
  // Test T for age_type here.
}


In D2 this won't be possible for much longer, since typedef is going away. But you can fake it:

  template Typedef(T, string name)
  {
      mixin("struct "~name~" { "~T.stringof~" x; alias x this; }");
  }

  mixin Typedef!(int, "age_type");
  age_type age(int i) { return age_type(i); }

If you're going to use it a lot, you can even automate it further:

  template NamedArg(T, string name)
  {
      mixin Typedef!(T, name~"_type");
      mixin(name~"_type "~name~"("~T.stringof~" t) {"
        ~" return "~name~"_type(t); }");
  }

  mixin NamedArg!(int, "age");
  mixin NamedArg!(string, "status");

  foo(2, &bar, age(10), status("down"));

-Lars

Reply via email to