如何在模板class的内部class写虚函数?

How to write virtual function in inner class of template class?

我的模板 class linearLinkedList<T> 有一个内部 class、myIterator,我想覆盖从 [=15= 继承的虚拟方法],但编译器将它们拒绝为 "templates may not be virtual." 基于 this question,不过,这似乎应该是可能的,因为它仅取决于 class 的类型。例如,我下面代码中的方法 foo 是合法的。如何实现内部的虚函数class?

template <class T>
class linearLinkedList
{
public:
...
virtual void foo(T data); //OK
simpleIterator<T> * iterator();
private:
...
class myIterator : public simpleIterator<T>
{
  public:
    myIterator(node<T> ** head);
    virtual ~myIterator(); //inherited from simpleIterator; error when implemented
  private:
    node<T> ** prev;
    node<T> ** next;
    //functions inherited from simpleIterator<T>:
    virtual bool hasNext_impl(); //error when implemented
    virtual T next_impl();
    virtual void remove_impl();
};
...
template<class T>
virtual linearLinkedList<T>::myIterator::~myIterator() { ... }
->
linearLinkedList.h:213:1: error: templates may not be âvirtualâ
virtual linearLinkedList<T>::myIterator::~myIterator()

本身不是函数模板的成员函数可以标记为 virtual,即使它是 class 模板的一部分,但是:

§ 7.1.2 [dcl.fct.spec]/p1:

Function-specifiers can be used only in function declarations.

function-specifier:
    inline
    virtual
    explicit

The virtual specifier shall be used only in the initial declaration of a non-static class member function; see 10.3.

也就是说,您应该从 class 定义外删除一个 virtual 关键字:

template<class T>
virtual linearLinkedList<T>::myIterator::~myIterator() { ... }
~~~~~~^ to be removed