Search code examples
c++templatesgeneric-programming

Compile-time parent child relationship through templates


This is mainly out of curiousity. I am wondering if there is a way to define a parent-type to child-type relationship at compile-time using templates.

template <class T>
struct parent_t {
  T *child;
};

template <class T>
struct child_t {
  T *parent;
};

It seems impossible due to infinite template recursion when trying to construct:

auto parent = new parent_t<child_t<parent_t< (... to infinity)

Solution

  • You can do it with an extra layer of indirection:

    template <typename T> struct parent;
    template <typename T> struct child;
    
    struct Traits {
        using p = parent<Traits>;
        using c = child<Traits>;
    };
    
    template <typename T>
    struct parent {
        typename T::c* child;
    };
    
    template <typename T>
    struct child {
        typename T::p* parent;
    };
    
    int main()
    {
         parent<Traits> p{nullptr};
         child<Traits> c{nullptr};
    
         c.parent = &p;
         p.child = &c;
    }