模板中的循环依赖 类
Circular dependency in template classes
我在处理类型的循环引用时遇到问题。对于以下内容的实施:
// 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_;
};
您可以在 OtherType
中使用 EnclosingType
声明(而不是定义),因为您是通过指针或引用来引用它的。 EnclosingType<OtherType>
的定义需要 OtherType
的定义,因为它按值包含它。
我在处理类型的循环引用时遇到问题。对于以下内容的实施:
// 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_;
};
您可以在 OtherType
中使用 EnclosingType
声明(而不是定义),因为您是通过指针或引用来引用它的。 EnclosingType<OtherType>
的定义需要 OtherType
的定义,因为它按值包含它。