On Wednesday, November 10, 2010 06:16:05 spir wrote:
> On Wed, 10 Nov 2010 00:30:55 -0800
> 
> Jonathan M Davis <jmdavisp...@gmx.com> wrote:
> > On Tuesday 09 November 2010 23:55:26 spir wrote:
> > > Hello,
> > > 
> > > Is there a way for a func to hold 2 optional params of the same type?
> > > 
> > >   void f(int p, bool b1=false, bool b2=false) {
> > >   
> > >       writefln("p=%s b1=%s b2=%s", p,b1,b2);
> > >    
> > >    }
> > > 
> > > Or is there a workaroud?
> > 
> > Try compiling it. It works just fine.
> > 
> > You should be able to have multiple optional parameters, and their types
> > shouldn't matter. Where you get into trouble is if that function has
> > overloads which conflict. Since, in effect, by declaring
> > 
> > void f(int p, bool b1 = false, bool b2 = false)
> > 
> > you've declared
> > 
> > void f(int p, bool b1, bool b2)
> > void f(int p, bool b1)
> > void f(int p)
> 
> Precisely, what a clear exposure of the issue! Sorry, my question was far
> to imprecise. I cannot have void f(int p, bool b2) {}
> If I call it with a single bool param, then D logically maps it to b1. In a
> language with named params, one would simply write f(whatever, b2=true);
> 
> Is there any workaround?

I'm sure that you could find various ways to get around specific examples (such 
as 
using Steve's proposal of a bitfield for bools), but generally, that's just not 
how things work. D doesn't have named parameters. The type and order of 
parameters are what determines which function overload to use.

The best general case solution that I can think of is to use a struct that 
holds 
the parameters that you want to pass in. Have its fields default to whatever 
you 
want as the default and only set the fields that you want to set.

In the case of bools, you could use a bitfield as Steve suggests, or you could 
use named enums instead with yes and no (like Phobos does in several places) 
and 
then declare multiple versions of the functions where one takes both enums and 
one takes only the second one that the first takes. So, if your two bools 
indicated that you should go south and you should go fast, you'd do something 
like

enum GoSouth {no, yes};
enum GoFast {no, yes};

func(int p, GoSouth gs = GoSouth.no, GoFast gf = GoFast.no) { ... }
func(int p, GoFast gf) { ... } // likely assumes GoSouth.no


That doesn't really scale very well though. Using named enums instead of bools 
in some cases though can make code clearer.

In any case, the struct solution is the best that I can suggest for the general 
case, but really, D doesn't have named parameters. Things just don't work that 
way. So, trying to make things work that way is going to require bending over 
backwards on some level.

- Jonathan M Davis

Reply via email to