【问题标题】:Forward declare child class template前向声明子类模板
【发布时间】:2014-05-16 21:01:04
【问题描述】:

首先,感谢任何可以帮助我的人。我目前正在研究 XML 解析器。这是我不久前没有的:

class Root
{
    // bla bla
}

根是链表的第一项。它有一个指向第一个项目的指针,以及从列表中添加和删除项目的功能。

class Base
{
    // bla bla
}

Base 类是一个简单的 Item,带有一个指向下一个 item 的指针。

class Child : public Base
{
    // bla bla
};

Child 类派生自 Base 类,并包含数据(例如元素的名称和值以及我的 XML 文件的属性)。

class Derived_1 : public Child
{
    // bla bla
};

class Derived_2 : public Child
{
    // bla bla
};

派生类是我的属性和元素。 Elements 包含 Root 用于属性列表,另一个用于元素列表(因此我可以构建层次结构)。

我的基类需要包含 Root 的功能,但不能作为子类继承。所以我们在 Base 类中与 Root 函数“加为好友”。

class Base
{
    friend class Root
    // bla bla
}

最近,我们谈到了模板,并且不得不将它们集成到 XML 解析器中。因此,首先,我们在模板中转换了 Root 类。因此,Root 被用于两个 Derived 类,Base 类受到这种影响:

template< class T >
class Root
{
    // bla bla
}

-------------

class Derived_1;
class Derived_2;
class Child;

class Base
{
    friend class Root<Derived_1>
    friend class Root<Derived_2>
    friend class Root<Child>

    // bla bla
}

-------------

class Child : public Base
{
    // bla bla
};

到目前为止,没问题。我们必须转发声明 Derived 类以避免包含中的循环。然后,我们必须使 Base 类成为模板,所以我们有:

class Derived_1;
class Derived_2;
class Child;

template< class T >
class Base
{
    friend class Root<Derived_1>
    friend class Root<Derived_2>
    friend class Root<Child>

    // bla bla
}

-------------

class Child : public Base<Child>
{
    // bla bla
};

然后,问题出现了,我们让 Child 类成为模板,所以它变成了:

template< class T >
class Child : public Base<T>
{
    // bla bla
};

但是,Base 类中的前向声明已经不行了,我们声明友元类的方式也不行。我必须找到一种方法来转发声明 Child 类,但我看不出如何。到目前为止,我没有遇到任何困难,但在这里,我看不出它背后的逻辑。有人可以向我解释这里的工作方式吗(我不要求答案,我只需要复制/过去你告诉我的内容,但我想了解发生了什么。非常感谢任何帮助。

【问题讨论】:

标签: c++ xml templates forward-declaration


【解决方案1】:

您的困难似乎源于类和类模板之间的差异。特别是,为了使从类模板实例化的前向声明类型成为友元,您需要前向声明类模板:

template <class T> class Child;

然后你就可以加好友了:

template <class T> class Base
{
    friend class Child<T>; // or
    friend class Root< Child<T> >;
    : : :
};

但请注意,友谊是coupling 最紧密的形式,当有更好的方法可以达到目的时,应该避免。

【讨论】:

  • 哦,好的,我正在搜索 waaaaay 很远。我试图以这种方式转发声明子类:“模板 class Child;”,以及两个派生类,在基类中,我与它们“交朋友”(找不到一个更好的词)这样:“friend class Root>;”。最后,它比我想要的“更容易”。当我有时间时,我将不得不深入研究这一切。非常感谢。在修复了一些更适合修复此问题的问题后,它们不再是问题了。再次感谢。 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-11-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-22
  • 2016-12-29
  • 1970-01-01
相关资源
最近更新 更多