Optional extra return value? Multiple return values with auto?

Ali Çehreli acehreli at yahoo.com
Mon Jul 23 22:30:49 PDT 2012


On 07/23/2012 08:25 PM, ReneSac wrote:
> How I can return multiple values in D, but one of them being optional? I
> tried the 'out' hack to achieve multiple return values, but it didn't
> accepted a default argument: it needed a lvalue in the calling function.

Like in C and C++, functions in D can also have a single return value. 
The most common workaround in C and C++ has been an out parameter 
(pointer in C and pointer or reference in C++).

The options that I can think of:

- Return a struct (or a class) where one of the members is not filled-in

- Similarly, return a tuple

- Use an out parameter, which can have a default lvalue:

int g_default_param;

void foo(ref int i = g_default_param)
{
     if (&i == &g_param) {
         // The caller is not interested in 'i'

     } else {
         // The caller wants 'i'
         i = 42;
     }
}

void main()
{
     foo();

     int i;
     foo(i);
     assert(i == 42);
}

- Use some template trick where the caller specifies what he wants:

   result = foo();
   complex_result = foo!with_iterations_needed();

Thinking back, perhaps because C and C++ don't provide multiple return 
values, I never missed them. Although they were nice when coding in 
Python. :)

Ali


More information about the Digitalmars-d-learn mailing list