On Sunday, 20 January 2013 at 16:11:08 UTC, Philippe Sigaud wrote:
On Sun, Jan 20, 2013 at 5:01 PM, Phil Lavoie <[email protected]> wrote:

Is there also a way to extract per parameter information (ex: type) using
type deduction. Let me illustrate:

struct Toto( T1, T2 ) {
 alias Key = T1;
 alias Value = T2;
}

struct OuterToto( T ) if( isToto!T ) {
  T.Key key;
  T.Value value;
}

Imagine I would want that but without using inner aliases, is this possible?

Sure, the U... part is accessible inside the static if. Just define a
generic helper template:


struct Toto(First, Second)
{

}

template TemplateArguments(T)
{
    static if (is(T _ : a!(Args), alias a, Args...))
        alias TemplateArguments = Args;
    else
        alias TemplateArguments = void;
}

template TemplateName(T)
{
    static if (is(T _ : a!(Args), alias a, Args...))
        alias TemplateName = a;
    else
        alias TemplateName = void;
}

void main(string[] args)
{
    alias Type = Toto!(int, double);
    writeln(TemplateArguments!(Type).stringof);
    writeln(TemplateName!(Type).stringof);

    alias T = TemplateName!(Type);
alias Swapped = T!(double, int); // And you can use T as a template.
}

As you can see, you can even use the deduced template name.

YES, it works! I just didn't realized you could only use it inside the static ifs, thanks for pointing that out!

isInstanceOf( alias Template, T ) is nice but lacks support for expressions directly: but that ain't a big deal, example:

struct Pair( T1, T2 ) {...}

template isPair( alias T ) {
  static if( is( T ) ) {
    enum isPair = isInstanceOf!( Pair, T );
  } else {
enum isPair = isInstanceOf!( Pair, typeof( T ) ); //Must add this to support expressions.
  }
}

//Returns the type of the first term of the pair.
template FirstType( alias T ) if( isPair!T ) {
  static if( is( T _: Pair!Args, Args... ) ) {
    alias FirstType = Args[ 0 ];
  } else {
    alias FirstType = FirstType!( typeof( T );
  }
}

The D programming language ROCKS :).

Reply via email to