0

This code fails to compile:

class B;
class A{
  typedef int AThing;
  typedef B::BThing BThing;
};
class B{
  typedef int BThing;
  typedef A::Athing AThing;
};

Because A needs a typedef from B and B needs one from A.

What is the typical method for using typedefs that have circular dependancies?

DarthRubik
  • 3,927
  • 1
  • 18
  • 54
  • 1
    not a duplicate IMO, there are no header includes here, let alone circular dependencies in header includes – M.M Jul 04 '16 at 22:55
  • Dunno why I can't answer, so will do it here. This is definitely not a duplication, and pretty difficult question indeed! This case can be resolved by adding one more level of indirection: [see demo](https://godbolt.org/g/jx5IC9). I faced with pretty same case and I'm looking for more general and useful solution right now. – Trollliar Jan 21 '17 at 09:39
  • @Trollliar That is an interesting way of solving that problem.. – DarthRubik Jan 21 '17 at 13:33

2 Answers2

2

The typical solution for having circular typedef dependencies of this kind is to not have circular typedef dependencies of this kind. These kinds of circular typedef dependencies cannot be done in C++, so you have to rearrange your class hierarchy:

class B;

typedef int this_is_a_BThing;

class A{
  typedef int AThing;
  typedef this_is_a_Bthing BThing;
};
class B{
  typedef this_is_a_BThing BThing;
  typedef A::Athing AThing;
};
Sam Varshavchik
  • 114,536
  • 5
  • 94
  • 148
0

What is the typical method for using typedefs that have circular dependancies?

There's no such typical method, you cannot do that.

For cases how you can use forward declarations and expand dependent typedefs in scope of types see the answers from Resolve header include circular dependencies in C++.

The case you are introducing a typedef at class scope doesn't matter much about the fact that the compiler cannot resolve it from seeing a forward declaration.


The only way I can think of using typedefs is to use the Pimpl Idion and actually introduce them in the implementation only.

Community
  • 1
  • 1
πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190