c++ - 模板类中的循环依赖

标签 c++ templates circular-dependency

我在处理类型的循环引用时遇到了问题。对于以下内容的实现:

// Parent.h
template <typename OtherType>
class EnclosingType
{
public:
    typename OtherType type_;
};

class OtherType
{
public:
    EnclosingType & e_;
    OtherType (EnclosingType & e) : e_(e) {}
};

要求是 OtherType 引用 EnclosingType 的对象,以便它可以调用 EnclosingType 上的方法,而 EnclosingType 可以调用 OtherType 上的方法。主要目标是允许实现者提供他们自己的 OtherType 派生类型。

处理存在此类循环依赖的情况的最佳方法是什么? OtherType 的正确声明是什么? OtherType::EnclosingType 的正确声明是什么? Enclosing::OtherType::type_ 的正确声明是什么?我需要做的事情是否可行?

谢谢。

最佳答案

如果我假设你想要 OtherType包含对 EnclosingType<OtherType> 的引用,您可以执行以下操作:

// EnclosingType declaration
template <typename T>
class EnclosingType;

// OtherType definition
class OtherType
{
public:
  EnclosingType<OtherType> & e_;
  OtherType (EnclosingType<OtherType> & e) : e_(e) {}
};

// EnclosingType definition
template <typename T>
class EnclosingType
{
public:
    T type_;
};

您可以使用 EnclosingType OtherType 中的声明(相对于定义)因为您是通过指针或引用来引用它的。 EnclosingType<OtherType>的定义需要 OtherType 的定义因为它按值包含它。

关于c++ - 模板类中的循环依赖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38621991/

相关文章:

c++ - 涉及 iostream 和 wstring 的奇怪 C++ 行为

c++ - int(int)& 或 int(int) const & 是什么类型?

c++ - 对参数使用模板语法

c++ - friend 和模板类

php - 自定义 View 类显示 View 两次

scala - Scala 集合中的循环依赖

c++ - 如何扩展这个 C++11 事件系统来处理多个参数?

java - 将 C++ long 类型转换为 JNI jlong

database - 数据库是否接受循环引用?

从OO语言到C语言,如何避免循环依赖?