Search code examples
c++syntaxcircular-dependency

using a typedef from another class in a circular manner


This is a question to see the limits of the C++ language.

Most circular class dependencies can be solved with forward declarations and pointers.

But I wonder if this can be solved somehow:

struct Y; // forward declaring Y does not solve the problem

struct X {
  using T = int;
  using Other = Y::T; //error: incomplete type 'Y' named in nested name specifier
};

struct Y {
  using T = float;
  using Other = X::T;
};

Parsing it by a human eye, you can easily see that in this code X::Other could trivially be understood as float because Y::T does not depend on anything. However I do not know of any syntax that would allow to "forward declare a typedef", something like typename Y::T = float; (but there are always unexplored dark corners of C++) or any method or idiom that would allow the above typedefs.

So is there a technique to resolve the above? (specifically: each class using the other class's typedef - wthout moving the typedef outside the class)


Solution

  • You could make X a template struct. Something like this.

    template <typename YType>
    struct X {
      using T = int;
      using Other = typename YType::T;
    };
    
    struct Y {
      using T = float;
      using Other = X<Y>::T;
    };
    
    int main()
    {
        X<Y> x;
    }
    

    It is not a perfect solution, but when you have corner cases like this, sometimes you need to do hacks.