0

I'm having trouble with a circular reference of types. For an implmentation of the following:

// Parent.h
template <typename OtherType>
class EnclosingType
{
public:
    typename OtherType type_;
};

class OtherType
{
public:
    EnclosingType & e_;
    OtherType (EnclosingType & e) : e_(e) {}
};

The requirement is that OtherType take a reference to an object of EnclosingType so that it can invoke methods on EnclosingType, and EnclosingType can invoke methods on OtherType. The main goal is to allow implementers to supply their own OtherType-derived types.

What is the best way to handle the case where this type of circular dependency exists ? What is the proper declaration of OtherType ? What is the proper declaration of OtherType::EnclosingType ? What is the proper declaration of Enclosing::OtherType::type_ ? Is what I need to do even possible ?

Thanks.

  • 1
    `EnclosingType` is not a type; it's a template. And it has no methods. `OtherType` has no methods either. I don't understand what you're trying to do. – melpomene Jul 27 '16 at 19:54
  • check CRTP, it might be helpful for this scenario though I'm not so sure whether it'll help you to solve your issue. https://en.wikipedia.org/wiki/Curiously_recurring_template_pattern – Paul Varghese Jul 27 '16 at 19:55

1 Answers1

1

If I make the assumption that you wanted OtherType to contain a reference to EnclosingType<OtherType>, you can do the following:

// EnclosingType declaration
template <typename T>
class EnclosingType;

// OtherType definition
class OtherType
{
public:
  EnclosingType<OtherType> & e_;
  OtherType (EnclosingType<OtherType> & e) : e_(e) {}
};

// EnclosingType definition
template <typename T>
class EnclosingType
{
public:
    T type_;
};

You can use the EnclosingType declaration (as opposed to definition) in OtherType since you are referencing it via a pointer or reference. EnclosingType<OtherType>'s definition needs the definition of OtherType because it includes it by value.

md5i
  • 3,018
  • 1
  • 18
  • 32
  • Thanks, that's helpful and I'm accepting this as the answer. However, I'll beg your indulgence and extend the question a bit . What would be the pattern if EnclosingType required multiple (finiite) inner types (e.g. OtherType1, OtherType2). In this scenario, the consumer might only elect to derived from OtherType1, and use a default implementation of OtherType2. The requirement of OtherType{n} instances holding a reference to an EnclosingType instance would still be present. Thoughts on this ? – user1612443 Jul 27 '16 at 20:29
  • That's another question. Please post it separately so that others may benefit later. – jonspaceharper Jul 27 '16 at 22:59