On Monday, 23 July 2012 at 13:32:54 UTC, Philippe Sigaud wrote:
As an aside to a reflection-related train of thought, I tired again to get a templated type's parameter list.

I mean, given

class C(T) { T t; }

Drat, 'tab' is dangerous with the forum interface, sorry for that.

So given C above and

auto c = new C!(int)();

I want a template that, given typeof(c), gives me back 'C' and 'int'.
is() is our friend here, notably the new T... extension:

import std.typetuple;
template Composition(T) if (isComposite!T)
{
static if (is(T comp == Name!(U), alias Name, U) || is (T comp == Name!(U), alias Name, U...))
        alias TypeTuple!(Name, U) Composition;
}

(isComposite!T is the same check with is())

Works beautifully:

auto t = tuple(1,"abc", 'c');

writeln(Composition!(typeof(t)).stringof); // ("Tuple(Specs...)", int, string, char)

So, I get "Tuple(Specs...)" (the template name) and the arguments. Nice!

Except, this does not work for 2-args templates. I thought the U... branch would get them, but apparently, U... means 'with a template param tuple' very strictly. No problem, I'll just add the 2, 3 and 4-args cases, that should be enough.

template Composition(T) if (isComposite!T)
{
static if (is(T comp == Name!(U), alias Name, U) || is (T comp == Name!(U), alias Name, U...))
        alias TypeTuple!(Name, U) Composition;
    else static if (is(T comp == Name!(U,V), alias Name, U, V))
        alias TypeTuple!(Name, U,V) Composition;
else static if (is(T comp == Name!(U,V,W), alias Name, U, V, W))
        alias TypeTuple!(Name, U,V,W) Composition;
...
}

(and isComposite accordingly).

Right. Except, this only gets template instantiations with pure types as parameters. Things like std.algorithm.map which take a function by name are out.

OK... So, I'll add also alias overloads. Hmm, Pure Type / Alias : 2 possibilities, so for 3 args that's 8 different tests to do + 4 for 2-params, + 2 for the single param and the tuple... Except, you can have a tuple also in 2-params and 3-params templates.

Also, what about value template parameters? I tested, this does not work when passed strings or ints, or whatever. I should test for them also.

Argh, so it's more 10 different possibilities per slot, the n-th power for n args.

No way am I generating a template with more than a thousand(!) is() tests in it!

Can someone offer me some advice on this? My old version that cheated with the type .stringof suddenly seems so much better.

Philippe

Reply via email to