【问题标题】:C++ Non-Template Used as Template - Nested Template Classes [duplicate]用作模板的C ++非模板-嵌套模板类[重复]
【发布时间】:2020-12-16 03:07:21
【问题描述】:

我知道有人在这方面提出过类似的问题,但我似乎无法找到解决我确切问题的方法。我有一个 LinkedListLinkedListIterator 类的结构。

template <typename T>
class LinkedList
{
public:
  template <typename NodeType>
  class LinkedListIterator
  {
    public:
      const LinkedListIterator<NodeType>& operator++();
  }
};

我正在尝试在单独的文件中实现operator++() 函数,我的尝试如下。

template <typename T>
template <typename NodeType>
const typename LinkedList<T>::LinkedListIterator<NodeType>&
LinkedList<T>::LinkedListIterator<NodeType>::operator++()
{
 // Implementation here
}

现在当我尝试使用这个类时,我的编译器会抛出一个错误,提示 non-template ‘LinkedListIterator’ used as template。现在我知道我必须在这个函数的定义中使用typename,因为我有依赖范围发生。但我似乎无法解决这个问题。我不明白这如何被视为non-template

【问题讨论】:

标签: c++ templates iterator typename


【解决方案1】:

在 LinkedListIterator 之前添加模板关键字,以便编译器知道它是模板而不是例如一个字段

template <typename T>
template <typename NodeType>
const typename LinkedList<T>::template LinkedListIterator<NodeType>&
LinkedList<T>::LinkedListIterator<NodeType>::operator++()
{
  // Implementation here                                                                                                                                                                                                                    
}

【讨论】:

  • 谢谢,这似乎成功了。但我有一个后续问题。我认为这就是包含 typename 关键字的意义所在?你介意解释一下为什么我需要 typename 关键字和模板以及我什么时候单独使用它们吗?
  • 当你省略 typename 时编译器会解释一下:error: need ‘typename’ before ‘LinkedList&lt;T&gt;::LinkedListIterator&lt;NodeType&gt;’ because ‘LinkedList&lt;T&gt;’ is a dependent scope const LinkedList&lt;T&gt;::template LinkedListIterator&lt;NodeType&gt;&amp;
猜你喜欢
  • 1970-01-01
  • 2016-05-23
  • 2018-11-08
  • 1970-01-01
  • 2018-11-26
  • 1970-01-01
  • 1970-01-01
  • 2014-02-22
  • 2011-05-04
相关资源
最近更新 更多