February 09, 2012
Hi,

named parameters have been discussed awhile ago and it seems to me that they won't get into the language soon. I came up with a workaround that makes it possible to use them with some extra typing.

Suppose we have a function

foo(int a, int b, string c, MyStruct d, MyClass e);

and want to call with with named parameters. It is possible to write a wrapper function as follows

foo(N)(N n)
{
  foo(
    n.has!"a"() ? n.get!"a"() : 42, // 42 is the default parameter
    n.get!"b"(), // Complain if b is not given
    n.has!"c"() ? n.get!"c"() : "foo",
    n.has!"d"() ? n.get!"d"() : MyStruct(),
    n.has!"e"() ? n.get!"e"() : new MyClass()
 );
}

and then call it

foo(named!"c,b,e"("Foo", 0, new MyClass()));

With some more work we could also allow

foo(named!"c"("Foo"), named!"b"(0), named!"e"(new MyClass()));

All this can be handled by a templated Wrapper-Object that is created
by named()(). When doing the code generation of the wrapper object via
a mixin, we could also allow ref parameters (with named!"ref
e"(my_class) and by storing a pointer).

Of course, the code for the wrapper can be inlined because the presence of every parameter can be decided at compile time.

Any ideas?

Best regards,

Matthias