named arguments (C++) - Something D could learn from
aliak
something at something.com
Tue Dec 18 18:23:20 UTC 2018
On Tuesday, 18 December 2018 at 11:15:26 UTC, Simen Kjærås wrote:
> 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
Woah... that's quite neat.
I feel like this is how std.typecons.Flag should have been made!!
I played around with it for a bit, and if there was a way to get
some better error messages then that could be quite nice to use!
- i dunno, maybe through some static assert on the "string
names"s being passed in or something...
Cheers,
- Ali
More information about the Digitalmars-d
mailing list