0

Is there a way to break circular dependencies like the following without moving both using/typedef aliases outside classes?

// header A.h
#ifdef A
#define A
#include "B.h"
class A {
  using ID = uint32_t;
  void some_func(B::ID id);
};
#endif A


// header B.h
#ifdef B
#define B
#include "A.h"
class B {
  using ID = uint64_t;
  void some_func(A::ID id);
};
#endif B


// main.cpp
#include "A.h"
int main() {...}

Assume guard #ifdefs are present and ID can be a more complex type (a struct etc.).

Edit: a bit of clarification: alias names are not necessarily the same (i.e. not ID).

Modified example:

// header A.h
#ifdef A
#define A
#include "B.h"
class A {
  using SomeAliasInA = uint32_t;
  void some_func(B::SomeAliasInB id);
};
#endif A


// header B.h
#ifdef B
#define B
#include "A.h"
class B {
  using SomeAliasInB = std::string;
  void some_func(A::SomeAliasInA id);
};
#endif B

1 Answers1

0

Create an external file for type definitions:

template<typename T>
struct types{};

class A;
class B;

template<>
struct types<A>{
    using alias = std::string;
};

template<>
struct types<B>{
    using ID = bool;
    using alias_2 = int;
    using alias_3 = short;
};

You can then use it like so:

class A{
    void foo(types<B>::ID id);
};
class B{
    void foo(types<A>::alias id);
};
Quest
  • 2,764
  • 1
  • 22
  • 44
  • Thanks for the answer. Your solution seems reasonable when aliases have the same name. I've updated the question with a clarification. – Jimmy Bazooka Jan 04 '17 at 09:19
  • @JimmyBazooka The same answer apply, you can have as many typedefs or aliases as you want in `types` struct. – Quest Jan 04 '17 at 14:00