Test for self referential templated Class

Don nospam at nospam.com.au
Mon Jun 30 13:27:50 PDT 2008


Manfred_Nowak wrote:
> Michel Fortin wrote:
> 
>> You could add a dummy member in C!(T) and check for its presence. 
> 
> Yes. That seems to be less hackish than what Robert suggested. But 
> still no possibility to fetch a non trivial depth of recursion.

I've done this sort of thing with a recursive mixin.
The basic idea is something like
char [] testRecursion(bool done)
{
   return done? `true`: `mixin("testRecursion( XXX)`;
}

template isRecursive(T)
{
     const bool isRecursive = mixin(testRecursion());
}

where XXX is some expression involving T. It works because if the 
condition isn't true, the recursive bit is just a string which is never 
parsed. But if it is true, it gets mixed in recursively.

There might be something a bit less hacky for this situation*. But the 
recursive mixin trick will work even for fiendishly difficult cases. You 
can hide any old garbage that wouldn't normally compile for ANY reason.

* for D2.0, you can probably use __traits(compiles, XXX)
> 
> import std.metastrings;
> private typedef int TID; // TypeID for checking purposes
> class C(T){
>   alias .TID TID;
>   pragma( msg, Format!(is( T.TID== TID)));
> }
> class D{
>   private typedef int TID;
> }
> void main(){
>   auto d= new C!( D);
>   pragma( msg, "d done");
>   auto c1= new C!(int);
>   pragma( msg, "c1 done");
>   auto c2= new C!( C!(int));;
>   pragma( msg, "c2 done");
>   auto c3= new C!( C!( C!(int)));
>   pragma( msg, "c3 done");
> }
> 
> -manfred



More information about the Digitalmars-d mailing list