Optional parameters?

Jacob Carlborg doob at me.com
Sun Apr 1 16:00:25 UTC 2018


On 2018-04-01 17:54, Steven Schveighoffer wrote:
> I currently have a situation where I want to have a function that 
> accepts a parameter optionally.
> 
> I thought maybe Nullable!int might work:
> 
> void foo(Nullable!int) {}
> 
> void main()
> {
>     foo(1); // error
>     int x;
>     foo(x); // error
> }
> 
> Apparently, I have to manually wrap an int to get it to pass. In other 
> languages that support optional types, I can do such things, and it 
> works without issues.
> 
> I know I can do things like this:
> 
> void foo(int x) { return foo(nullable(x)); }
> 
> But I'd rather avoid such things if possible. Is there a way around 
> this? Seems rather limiting that I can do:
> 
> Nullable!int x = 1;
> 
> but I can't implicitly convert 1 to a Nullable!int for function calls.

Yeah, D doesn't allow user defined implicit conversions, which I think 
is required for this. I would make function overloading even more 
complex than it is today.

Although it would be really handy for cases like this.

-- 
/Jacob Carlborg


More information about the Digitalmars-d-learn mailing list