Dream Feature Regarding Default Arguments

Nick Sabalausky SeeWebsiteToContactMe at semitwist.com
Sat Apr 5 18:26:17 PDT 2014


I realize this isn't the time for such a thing to be added to D, but I 
thought I'd put the idea out there, FWIW:

I find myself frequently needing to design APIs that work like this:

     func( [optionalFoo], [optionalBar] )

Typically, that's not permitted in C-style languages, including D. They 
only allow this:

     func( [optionalFoo, [optionalBar]] )

This restriction is necessary because, if the params take compatible 
types (ex: func(int,int)) and the caller only provides one, then there's 
no other way to tell which parameter the caller was trying to provide.

But when the params are different incompatible types, there's no 
ambiguity. This leads to the following awkward, noisy, hard-to-read 
idioms which I find myself using very frequently (I'm pretty sure I've 
seen it in Phobos, too):

     void func(Foo foo=defaultFoo, Bar bar=defaultBar) {...}
     void func(Bar bar) {
         func(defaultFoo, bar);
     }

or:

     void func(Foo foo, Bar bar=defaultBar) {...}
     void func(Bar bar=defaultBar) {
         func(defaultFoo, bar);
     }

Worse still, if there are other overloads, params, templates, etc, then 
this gets REALLY hairy, REALLY fast. It becomes very difficult to read, 
difficult to test, difficult to maintain, and difficult for users to 
grok the function's generated documentation.

Such a big mess for such a trivially simple API:

     func( [optionalFoo], [optionalBar] )

It would be *fantastic* if D recognized the disambiguation of using 
incompatible types and permitted this:

     interface Foo {}
     interface Bar {}
     class FooBar : Foo, Bar {}

     void func(Foo foo=someFoo, Bar bar=someBar) {...}

     func(myFoo); // Unambiguous, OK
     func(myBar); // Unambiguous, OK
     func(myFooBar); // Ambiguous, ERROR


More information about the Digitalmars-d mailing list