As discussed in DConf2015: Python-like keyword arguments

Atila Neves via Digitalmars-d digitalmars-d at puremagic.com
Thu May 28 15:35:12 PDT 2015


I might do a blog post on this, but here's some POC code:

import std.stdio;
import std.range;
import std.typetuple;
import std.traits;
import std.conv;


struct Foo { int i; }
struct Bar { int i; }
struct Baz { int i; }


void func(Foo foo, Bar bar, Baz baz) {
     writeln("foo is ", foo);
     writeln("bar is ", bar);
     writeln("baz is ", baz);
}


auto getStrArgs(alias F, T...)() {
     string[] strArgs;

     foreach(i, ParamType; ParameterTypeTuple!F) {
         enum index = staticIndexOf!(ParamType, T);

         static if(index != -1) {
             strArgs ~= "args[" ~ index.to!string ~ "]";
         } else {
             strArgs ~= ParamType.stringof ~ ".init";
         }
     }

     return strArgs;
}

auto kwargs(alias F, T...)(T args) {
     enum strArgs = getStrArgs!(F, T);
     mixin("return F(" ~ strArgs.join(",") ~ ");");
}

void main() {
     kwargs!func(Bar(2), Baz(3), Foo(1));
     kwargs!func(Baz(3), Foo(1));
}


More information about the Digitalmars-d mailing list