Passing function parameters by name
Bill Baxter
dnewsgroup at billbaxter.com
Thu Dec 6 00:58:40 PST 2007
Janice Caron wrote:
> On Dec 5, 2007 1:48 PM, renoX <renosky at free.fr> wrote:
>> I could ask the opposite question: why should we restrict the API to the function and object name instead of using the full data that we have?
>
> Another thought. If the name were part of the API then could one
> overload functions by parameter name? e.g.
>
> void f(int a) { /* do something */ }
> void f(int b) { /* do something different */ }
>
> After all, if the name were part of the API, then they have different APIs.
>
> I'm not convinced that this is a good idea. It's also not the only
> alternative. I have in the past written programs which take parameters
> of the same underlying type in any order, using only D-as-it-is-now
> (or C++), and it's not so hard. For example, suppose you want a
> function that looks like
>
> MyDate makeDate(int month, int day, int year)
>
> but you think callers might get confused about what order to pass the
> parameters in (European date order, American date order, YMD date
> order, whatever...)
>
> typedef int Year;
> typedef int Month;
> typedef int Day;
>
> MyDate makeDate(Year y; Month m, Day d) {/*...*/ }
> MyDate makeDate(Year y, Day d, Month m) { return MyDate(y,m,d); }
> MyDate makeDate(Day d, Month m, Year y) { return MyDate(y,m,d); }
> MyDate makeDate(Month m, Day d, Year y) { return MyDate(y,m,d); }
>
> That forces callers to name their arguments, as in:
>
> MyDate date = makeDate(cast(Day)11, cast(Month)11, cast(Year)1999);
>
> If you wanted, you could also add a "default" function that took ints
> but required parameters in the right order.
>
> And that, basically, is problem solved, as far as I can see.
Gee that's so clean! Not.
You've taken one simple function and turned it into 4 functions plus 3
extra types.
It's a workaround at best.
--bb
More information about the Digitalmars-d
mailing list