【问题标题】:Initialization of a struct defined in a templated parent class在模板化父类中定义的结构的初始化
【发布时间】:2020-06-30 17:47:05
【问题描述】:

我在父类的受保护部分中定义了一个结构,我想在继承的类中使用它。

如果父/子类不是模板类,这将按预期工作。但不会按如下方式编译。

具体来说,编译器(clang 8.0.1)报告:

inheritance_example.cpp:33:26: error: unknown type name 'Node'
        this->head = new Node(toAdd);

根据我的阅读,我猜测模板类型规范没有分配给Node,因此没有被继承的类找到,但尝试了我在这种情况下找到的修复(即像using Parent<T>::Node 那样添加一些东西,或者在调用 Node 构造函数时添加一个类型说明符),对我不起作用。

关于如何解决此问题的任何想法?

#include<iostream>

template <class T>
class Parent 
{
protected:
   struct Node
   {
      Node(int value) 
      {
         this->data = value;
         this->next = nullptr;
      };

      ~Node() {};
      Node* next;
      int data;
   };

   Node* head;

public:
   Parent() {};
   ~Parent() {};
};

template <class T>
class Child : Parent<T>
{
public:

   Child() 
   {
      this->head = nullptr;
   };

   ~Child()
   {
      delete this->head;
      this->head = nullptr;
   };

   void dummyAdd(T toAdd) {
      this->head = new Node(toAdd);
   };

   void dummyPrint() 
   {
      std::cout << this->head->data << std::endl;
   };
};

int main() 
{
   Child<int> t;
   t.dummyAdd(5);
   t.dummyPrint();
   return 0;
}

【问题讨论】:

  • this-&gt;head = new typename Parent&lt;T&gt;::Node(toAdd);?
  • 成功!谢谢你:)
  • @ioums 您应该将其添加为答案。
  • 类似 question 有同样的问题 - 需要使用 typename 关键字。

标签: c++ class c++11 templates class-template


【解决方案1】:

为了将评论打包成答案!

Node 是一个依赖名称,因此您需要在此处使用 keyword typenamedummyAdd函数中的含义,你需要

void dummyAdd(T toAdd) 
{
   this->head = new typename Parent<T>::Node(toAdd);
   //               ^^^^^^^^^^^^^^^^^^^^ 
};

然而,这有点冗长/更多的打字。因此,在Child 中为Node 提供一个type alias 将是一个好主意。

template <class T>
class Child : Parent<T> 
{
   using Node = typename Parent<T>::Node;  // template type alias

public:
   void dummyAdd(T toAdd) 
   {
      this->head = new Node(toAdd);       // now you can this
   };

   // other code...
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多