Two things I thought would be simple

Jonathan M Davis newsgroup.d at jmdavisprog.com
Wed Mar 7 14:42:26 UTC 2018


On Wednesday, March 07, 2018 16:20:19 Shachar Shemesh via Digitalmars-d 
wrote:
> import std.traits;
> import std.stdio;
>
> void func(int a, int b=2, int c=3) {
>      return a+b+c;
> }
>
> void func2(Parameters!func args = ParameterDefaults!func) {
>      return func(args);
> }
>
> void main() {
>      writeln(func2(1));
>      writeln(func2(1,1));
>      writeln(func2(1,1,1));
> }
>
> So, this does not compile. I can do that with a mixin, but I would much
> rather not. Is there a non-Mixin method of copying not only the
> function's signature, but also its default values?

AFAIK, there's no way to get the values of default arguments with type
inferrence, and without that, you pretty much need a way to know what the
arguments are on your own - either by using mixins or by using known enums
that can be reused both in the function arguments and wherever it is that
you want to reuse them. Having some way to get at default arguments via
__traits may be a perfectly reasonable enhancement request. I don't know
enough about how that would be implemented to know whether it would be a
problem or not though.

> The second thing I thought would be simple is to refer to call a
> struct's member.
>
> struct S {
>      void func(int a) {
>      }
> }
>
> unittest {
>      alias v = S.func;
>
>      S s;
>      s.v(12); // No property v for type S
>      // UFCS to the rescue!
>      v(s, 12);
>      // function S.func(int a) is not callable using argument types (S,
> int)
>
>      // Maybe using getMember?
>      __traits(getMember, S, "func")(s, 12); // Same error
>      // Maybe without UFCS
>      s.__traits(getMember, S, "func")(12);
>      // identifier expected following ., not __traits
> }
>
> Am I missing something?

No. As I understand it, you need a delegate to do something like this. I
don't recall the technical details as to why if I ever knew, but I
definitely agree that it's annoying - especially with getMember.

- Jonathan M Davis



More information about the Digitalmars-d mailing list