Compilable Recursive Data Structure ( was: Recursive data structure using template won't compile)

Rob T rob at ucora.com
Thu Nov 8 20:57:46 PST 2012


There is clearly no recursion in the struct, it terminates at the 
pointers, therefore it is of finite and knowable size during 
compile time.

R looks like this if value is int

dlist!R = struct{ struct*, struct* }
R = struct{ int, struct{ struct*, struct* } }
node!R = struct{ struct{ int, struct{ struct*, struct* } }, 
struct*, struct* }

The the structs are now fully defined.

I will argue that there's actually no recursion in the definition 
when the definition is looked at from the POV of what the 
compiler should be seeing.

struct R =
{
    int = int; // STOP
    d_list!R =
    { node!(R)* = pointer; // STOP
      node!(R)* = pointer; // STOP
    } // STOP d_list is now 100% defined

We still need to know what node!R is in order to dereference the 
node!(R)* pointers inside d_list.

struct node!(R) =
{
   R = R; // STOP, R is fully defined already.
   node* = pointer; // STOP
   node* = pointer; // STOP
} // STOP node!(R) is 100% defined.

We now know the size and contents of R, d_list!R, and node!R, and 
we have all the information required to dereference the pointers 
properly.

How is the recursion in the definition stoping the compiler from 
doing its job?

Finally, take note that this altenate recursive definition 
compiles and works as expected:

struct node( P )
{
    P payload;
    node* pred;
    node* succ;
}

struct R( V )
{
    V value;
    alias node!R N;
    d_list!N Rlist;
}

struct d_list( N )
{
    N* head;
    N* tail;
    // even this works
    ref typeof(N.payload) getFirstValue(){
       return head.payload;
    }
}

The above template definitions define exactly the same structure 
as the original, it's just done in a different way, by supplying 
the entire node definition to the d_list instead of just the 
payload type.

Why should this version work and not the other?

--rt


More information about the Digitalmars-d-learn mailing list