named arguments (C++) - Something D could learn from
Jacob Carlborg
doob at me.com
Sun Dec 16 14:50:41 UTC 2018
On 2018-12-14 21:13, bauss wrote:
> In C++ you can achieve named arguments using templates and operator
> overload:
>
> It's sad that D is still against having named arguments, but it's
> possible in something that D thrives to be better than.
>
> https://www.fluentcpp.com/2018/12/14/named-arguments-cpp/
>
> I assume this is not possible to port to D because D doesn't do operator
> overload in the same way C++ does, correct?
>
> I still think named arguments should be something to consider
> implementing for D, but since everything requires a DIP and it's very
> hard to write a DIP that's proper for such a thing then I guess it'll
> just be a dream, forever.
Here's a simple version in D that doesn't require to declare a variable
for each name, does not support reordering names:
void foo(int a)
{
writeln(a);
}
void bar(NamedArgument!("b", int) b)
{
writeln(b);
}
struct NamedArgument(string name, T)
{
T value;
alias value this;
}
struct NamedArgumentProxy
{
auto opDispatch(string name, T)(T value) const
{
return NamedArgument!(name, T)(value);
}
}
immutable NamedArgumentProxy na;
void main()
{
foo(na.a = 3); // the name "a" here doesn't matter, it can be anything
foo(na.b = 4); // this has to be "b", otherwise it won't compile
}
https://run.dlang.io/is/zgejqi
--
/Jacob Carlborg
More information about the Digitalmars-d
mailing list