Optional out parameter of function

bearophile bearophileHUGS at lycos.com
Tue Nov 26 07:44:39 PST 2013


Joseph Rushton Wakeling:

> Suppose that I have an "out" parameter in a function:
>
>     int foo(in int i, out int j)
>     {
>         j = /* something */;
>         return /* whatever */;
>     }
>
> Is there any way to mark that out parameter as optional, i.e. 
> so that it only gets written to/used if a corresponding 
> parameter is passed to the function?

One simple solution is to define two overloaded functions, one 
with and one without the j argument.

If you want a single function, dropping out you can write:

int foo(size_t N)(in int i, int[N] j...)
if (N < 2) {
     static if (N == 1)
         j[0] = i;
     return i;
}

void main() {
     auto r1 = foo(1);
     int x;
     auto r2 = foo(1, x);
}

Bye,
bearophile


More information about the Digitalmars-d-learn mailing list