Pretty please: Named arguments
Steven Schveighoffer
schveiguy at yahoo.com
Mon Feb 28 04:46:55 PST 2011
On Mon, 28 Feb 2011 07:41:06 -0500, Michel Fortin
<michel.fortin at michelf.com> wrote:
> On 2011-02-28 02:03:46 -0500, Bekenn <leaveme at alone.com> said:
>
>> Potential problems: The only problems I can foresee here are
>> variations on the situation when there are two (or more) versions of a
>> function with the same number, type, and names of parameters, but in
>> non-matching order, like this:
>> void func(int a, char b);
>> void func(char b, int a);
>> In such a case, the compiler should diagnose an error if named
>> arguments are employed.
>> Thoughts?
>
> Another problem is what happens if you override a function by using
> different parameter names. For instance:
>
> class A {
> void func(int foo);
> }
> class B : A {
> void func(int bar);
> }
>
> Currently, the above is allowed. Would it now become an error?
>
> I think it'd be much easier to support named arguments if we didn't
> allow reordering. I know I'm stripping the proposal from one of its main
> benefits, but I think the essence remains. This would make the rather
> common pattern of adding a comment for each argument compiler-verifiable
> without disrupting things too much:
>
> draw(null, // text
> null, // font
> 12, // size
> 0, // flags
> );
>
> draw(text: null,
> font: null,
> size: 12,
> flags: 0);
>
> It would be implemented as a check for equality of the argument names
> after overload resolution. No ABI change, no interaction with
> overloading, just an extra check that if an argument name is specified
> it must match the one in the declaration.
>
> There'd still be a funny interaction with overriding (see my first
> example), but you can always leave your argument unnamed if the
> definition keep changing the name in unpredictable ways.
>
All these 'what if' ambiguities are simple to resolve -- if you use
positional arguments, it works. If you use named arguments, and it
matches more than one overload, it fails.
In fact, the case you give is unambiguous -- if you have an A, you can use
foo, if you have a B, you can use bar. Note that the confusion is all to
the person, and is completely avoidable. It's like naming your arguments
xy234m5 -- nobody knows what that means, so just choose a better name.
But it's not illegal.
I would say this would be a huge improvement to D. But I would also say
from my recollection, Walter is very against this. I think it would take
a motivated developer creating a pull request to get it done...
-Steve
More information about the Digitalmars-d
mailing list