【问题标题】:C++ circular dependency on public aliases (typdef/using) defined inside a class/structC++ 对在类/结构中定义的公共别名(typdef/using)的循环依赖
【发布时间】:2017-05-18 10:00:15
【问题描述】:

有没有办法在不将 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() {...}

假设守卫#ifdefs 存在并且ID 可以是更复杂的类型(struct 等)。

编辑:澄清一点:别名不一定相同(即不是ID)。

修改示例:

// 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

【问题讨论】:

    标签: c++ include using circular-dependency


    【解决方案1】:

    为类型定义创建一个外部文件:

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

    然后你可以像这样使用它:

    class A{
        void foo(types<B>::ID id);
    };
    class B{
        void foo(types<A>::alias id);
    };
    

    【讨论】:

    • 感谢您的回答。当别名具有相同名称时,您的解决方案似乎是合理的。我已通过澄清更新了问题。
    • @JimmyBazooka 同样的答案适用,您可以在types struct 中拥有任意数量的 typedef 或别名。
    猜你喜欢
    • 1970-01-01
    • 2013-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-21
    • 1970-01-01
    相关资源
    最近更新 更多