Last active
August 29, 2015 14:21
-
-
Save esnya/2c5745d8262487e8e2ab to your computer and use it in GitHub Desktop.
D言語で名前付き引数?
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module namedparam; | |
import std.stdio; | |
import std.traits; | |
import std.typecons; | |
template Arg(alias T, size_t N = 0) if (!is(typeof(ParameterDefaultValueTuple!T[N]))) { | |
alias Arg = Arg!(T, N + 1); | |
} | |
template Arg(alias T, size_t N = 0) if (is(typeof(ParameterDefaultValueTuple!T[N]))) { | |
alias Identifiers = ParameterIdentifierTuple!T[N .. $]; | |
alias Defaults = ParameterDefaultValueTuple!T[N .. $]; | |
alias Values = typeof(tuple!Identifiers(Defaults)); | |
struct Impl { | |
Values values = tuple!Identifiers(Defaults); | |
alias FieldType(string Field) = typeof(mixin("values." ~ Field)); | |
ref opCall() { | |
return values; | |
} | |
auto opDispatch(string Field)(FieldType!Field value) { | |
mixin("values." ~ Field) = value; | |
return this; | |
} | |
} | |
auto Arg() { | |
Impl arg; | |
return arg; | |
} | |
} | |
unittest { | |
auto foo(int req, int opt_a = 1, float opt_f = 1.0f, char opt_c = 'a', string opt_s = "hoge") { | |
return tuple(req, opt_a, opt_f, opt_c, opt_s); | |
} | |
assert(foo(123, 10) == tuple(123, 10, 1.0f, 'a', "hoge")); | |
assert(foo(456, Arg!foo.opt_c('c').opt_f(3.0f).opt_s("hogehoge")().expand) == tuple(456, 1, 3.0f, 'c', "hogehoge")); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment