Thread overview
function returning a tuple
Mar 15, 2008
Extrawurst
Mar 17, 2008
Russell Lewis
Mar 17, 2008
Koroskin Denis
Mar 17, 2008
Koroskin Denis
March 15, 2008
- Functions returning Tuples -

Is this planned to be implemented in D2.x ?
March 17, 2008
Extrawurst wrote:
> - Functions returning Tuples -
> 
> Is this planned to be implemented in D2.x ?

While I look forward to the day when this is eventually supported by the language, you can already do it by hand.  I have this common template which I include in my projects:

	struct Structize(TYPE_TUPLE)
	{
		TYPE_TUPLE fields;
	}

So you can do:
	Structize!(int,char) foo()
	{
		Structize!(int,char) ret;
		ret.fields[0] = 1234;
		ret.fields[1] = 'a';
		return ret;
	}
March 17, 2008
On Sat, 15 Mar 2008 05:33:07 +0300, Extrawurst <spam@extrawurst.org> wrote:

> - Functions returning Tuples -
>
> Is this planned to be implemented in D2.x ?

Functions return values, not types. You can use templates for this. An example from Phobos std.traits:

/***
 * Get the types of the paramters to a function,
 * a pointer to function, or a delegate as a tuple.
 * Example:
 * ---
 * import std.traits;
 * int foo(int, long);
 * void bar(ParameterTypeTuple!(foo));      // declares void bar(int, long);
 * void abc(ParameterTypeTuple!(foo)[1]);   // declares void abc(long);
 * ---
 */
template ParameterTypeTuple(alias dg)
{
    alias ParameterTypeTuple!(typeof(dg)) ParameterTypeTuple;
}

/** ditto */
template ParameterTypeTuple(dg)
{
    static if (is(dg P == function))
	alias P ParameterTypeTuple;
    else static if (is(dg P == delegate))
	alias ParameterTypeTuple!(P) ParameterTypeTuple;
    else static if (is(dg P == P*))
	alias ParameterTypeTuple!(P) ParameterTypeTuple;
    else
	static assert(0, "argument has no parameters");
}

Now having any function pointer or a delegate you can get its arguments as a tuple:

void testDelegate(DelegateType)(DelegateType dg)
{
    alias ParameterTypeTuple!(DelegateType) Arguments;

    // check that num args == 2
    static assert(Arguments.length == 2);

    // first param is an int
    static assert(is(Arguments[0] == int));

    // second one is a reference type
    static assert(is(Arguments[0] : Object));

    dg(0, null);
}
March 17, 2008
Well, I am wrong. There _IS_ a future direction to support returning tuples from functions. :)

http://www.digitalmars.com/d/2.0/tuple.html