简体   繁体   English

C ++对类/结构内定义的公共别名(typdef / using)的循环依赖

[英]C++ circular dependency on public aliases (typdef/using) defined inside a class/struct

Is there a way to break circular dependencies like the following without moving both using/typedef aliases outside classes? 有没有一种方法可以打破如下所示的循环依赖关系,而无需在类外移动using/typedef别名?

// 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 #ifdef s are present and ID can be a more complex type (a struct etc.). 假设存在警卫#ifdef ,并且ID可以是更复杂的类型( struct等)。

Edit: a bit of clarification: alias names are not necessarily the same (ie not ID ). 编辑:需要澄清:别名不一定相同(即,不是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

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);
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM