function returning a tuple

Koroskin Denis 2korden+dmd at gmail.com
Mon Mar 17 05:02:24 PDT 2008


On Sat, 15 Mar 2008 05:33:07 +0300, Extrawurst <spam at 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);
}



More information about the Digitalmars-d mailing list