Double face templates

Don nospam at nospam.com.au
Wed Oct 1 06:18:55 PDT 2008


bearophile wrote:
> BCS:
>> you might be able to use a form like this
>> template T(alias a)
>> {
>>     static if(is(a))
>>     {
>>        // stuff
>>     }
>>     else
>>        alias T!(typeof(a)) T;
>>     // or 'mixin T!(typeof(a));'
>> }
> 
> I think it doesn't work:
> 
> import std.stdio;
> 
> template ArrayType1(T: T[]) {
>     alias T ArrayType1;
> }
> 
> template Foo(alias x) {
>     static if(is(x))
>        alias ArrayType1!(x) Foo;
>     else
>        alias ArrayType1!(typeof(x)) Foo;
> }
> 
> void main() {
>     alias string[] Ts;
>     Ts s = ["aaaa", "bb"];
>     writefln(typeid( Foo!(s) ));
>     writefln(typeid( Foo!(Ts) ));
> }
> 
> But it doesn't matter much, I'll keep using just the version of the templates that take a type...
> 
> Bye and thank you,
> bearophile

It works if you change alias string[] Ts; into a typedef.

The reason is that aliases get resolved at a very early stage. There's 
no difference at all between string[] and Ts, and string is itself an 
alias, not a typedef. So Ts gets turned into char[][] before template 
lookup happens.

Built-in types can't be alias template parameters, unfortunately. Which 
kills the "double face template" idea.


More information about the Digitalmars-d-learn mailing list