Optional parameters?

Norm norm.rowtree at gmail.com
Mon Apr 2 04:41:13 UTC 2018


On Sunday, 1 April 2018 at 15:54:16 UTC, 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.
>
> -Steve

I don't know if this helps but when I hit this situation I 
usually resort to templates, e.g.

---
void foo(T)(T val = Nullable!int()) if(is(T : int) || is(T == 
Nullable!int))
{
   writeln(val);
}

void main()
{
    foo(1); // prints: 1
    int x;
    foo(x); // prints: 0
    auto val = Nullable!int(5);
    foo(val); // prints: 5
    foo(); // prints: Nullable.null
}
---

Cheers,
Norm


More information about the Digitalmars-d-learn mailing list