named arguments (C++) - Something D could learn from

Simen Kjærås simen.kjaras at gmail.com
Tue Dec 18 11:15:26 UTC 2018


On Tuesday, 18 December 2018 at 11:08:43 UTC, aliak wrote:
>> It's not even fewer characters! It's not trivial but it's 
>> possible to make the order not matter by using a templated 
>> implementation and aliasing it to `displayCoolName`.
>
> You also have to build it:
>
> func toHex(r: Int, g: Int, b: Int) -> Int {
>   return r << g << b;
> }
>
> As opposed to:
>
> struct R {
>   int value;
> }
> struct G {
>   int value;
> }
> struct B {
>   int value;
> }
> int toHex(R r, G g, B b) {
>   return r.value << g.value << b.value;
> }
>
> That's 67 vs 146 characters. Not to mention one pollutes the 
> namespace and one doesn't.

No need to pollute the namespace:

struct args {
     template opDispatch(string name) {
         alias opDispatch = Arg!name;
     }
}

struct Args(T) {
     template opDispatch(string name) {
         alias opDispatch = Arg!(name, T);
     }
}

struct Arg(string name) {
     static auto opAssign(T)(T value) {
         return Arg!(name, T)(value);
     }
}

struct Arg(string name, T) {
     T value;
     alias value this;
}

void fun(Args!int.foo foo) {} // Unfortunately requires 
repetition of arg name. :(

unittest {
     fun(args.foo = 3);
}

--
   Simen


More information about the Digitalmars-d mailing list