suggestion: default values
David B. Held
dheld at codelogicconsulting.com
Thu Apr 19 23:42:05 PDT 2007
bobef wrote:
> It would be nice if there was some character like $ or something, if used as function argument, the default value for this argument to be used. What I mean is this:
>
> void myfun(int a,char[] b,bool d=false,int e=55){}
>
> void main()
> {
> myfun(5,"5",$,$); // which should act like myfun(5,"5",false,55);
> }
While some languages provide named parameters, they tend to be langs
which encourage functions with many arguments. If you find you are
creating functions like this, you should first ask yourself if this is
the best way. If you decide that it is, one pattern to use is analogous
to the Builder pattern:
struct myFunArgs
{
int a;
char[] b;
bool d = false;
int e = 55;
}
void myfun(myFunArgs args) { ... }
myFunArgs args;
args.a = 5; args.b = "5";
myfun(args);
This is the *very* Poor Man's named parameters mechanism, but if you
have enough parameters to need named ones, then this probably isn't at
all burdensome (and may increase clarity).
Another alternative, if you are creating a library function that you
want to be *very* friendly, you can create a variadic type-safe template
function and parse the args inside the function (though this doesn't
work very well with args of the same type). Of course, you can use the
Perl convention of name, value pairs to make it completely general, but
that's not very elegant or idiomatic D style.
Dave
More information about the Digitalmars-d
mailing list