suggestion: default values

Daniel Keep daniel.keep.lists at gmail.com
Thu Apr 19 23:19:29 PDT 2007



Gregor Richards wrote:
> 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);
>> }
> 
> Probably a better example of why this would be helpful:
> 
> void myfunction(int a, char[] b, Foo veryComplicatedThing = default,
> bool d = true) {}
> 
> void main()
> {
>     myfunction(5,"5",$,false);
> }

We already have the perfect keyword for this: default.

void main()
{
    myfunction(5, "5", default, false);
}

A little more verbose, but pretty self-explanatory as to what it does.
Also, keep in mind that "$" already means array length inside of a
slice; I think it would be a bad idea to overload it with a completely
different meaning.

On a side note, you can do something vaguely similar using templated
functions and "typedef int DefaultType; const Default =
DefaultType.ini;" like so:

const int e_default = 55;

void myfunction(T)(T _e=Default)
{
    static if( is( T == DefaultType ) )
       e = e_default;
    else
       e = e;
}

Or somesuch; been a while since I did that :)

	-- Daniel

-- 
int getRandomNumber()
{
    return 4; // chosen by fair dice roll.
              // guaranteed to be random.
}

http://xkcd.com/

v2sw5+8Yhw5ln4+5pr6OFPma8u6+7Lw4Tm6+7l6+7D
i28a2Xs3MSr2e4/6+7t4TNSMb6HTOp5en5g6RAHCP  http://hackerkey.com/



More information about the Digitalmars-d mailing list