Function with default parameters

Simen kjaeraas simen.kjaras at gmail.com
Sat Sep 18 13:30:40 PDT 2010


Philippe Sigaud <philippe.sigaud at gmail.com> wrote:

> It seems doable to have some kind of function transformer (adaptor?) for
> this.
>
> from:
>
> int foo(int a = 0, int b = 1, double c = 0.0, bool d = false) { return  
> 1;}
>
> alias namedParams!foo nfoo;
>
> nfoo("d", true); // a = 0, b = 1, c = 0.0, d = true
> nfoo("d", true, "b", 100); // a=0, b=100, c=0.0, d=true
> nfoo(1, 2, "d", true);  // a=1, b=2, c=0.0, d=true
>
> That is, it expects some values, then string/values couples.
> Downside: in the above example, if foo accepts a string argument in  
> first or
> second position the "d" will be passed down as an argument...
>
> or, using AA syntax:
>
> nfoo(1, ["d":true],["b":100]);
>
> Would that be palatable? Because I think it's doable.
>
> To obtain the arguments names:
>
> int foo(int a, int b, double c = 0.0, bool d = true) { return 1;}
>
> template Name(alias foo) if (isCallable!foo)
> {
>     enum string Name = S!(foo.stringof);
> }
>
> template S(string s) // this template is just a trick because  
> foo.stringof
> directly displeases DMD
> {
>     enum string S = s;
> }
>
> writeln(Name!foo); // "int(int a, int b, double c = 0, bool d = true)"
>
> So this gives me:
>
> - the arguments names
> - which ones have default values
> - what is that default value
>
> The difficulty here is correctly parsing the ( ,,,) part, without getting
> desoriented by argument types that themselves use (,), like templated  
> types.

My main problem with these solutions is that they're largely runtime
solutions. Not that calling a function with named parameters is very likely
to happen in an inner loop, now I think of it...	

-- 
Simen


More information about the Digitalmars-d-learn mailing list