C++仿函数和模板:错误:'class List <T>'的声明

Eit*_*tan 4 c++ templates nested functor c++11

我在一个名为List :: find()的方法的模板类中有一个嵌套模板.这个方法得到一个函子作为输入,它是:"函数条件".

template<class T>
class List {
....
template<class Function>
Iterator find(Function condition) const;
....
};

template<class T, class Function>
typename List<T>::Iterator List<T>::find(Function condition) const {
   List<int>::Iterator it = this->begin();
   for (; it != this->end(); ++it) {
   if (condition(*it)) {
       break;
   }
   }
   return it;
}
Run Code Online (Sandbox Code Playgroud)

错误是:

..\list.h:108:62: error: invalid use of incomplete type 'class List<T>'
..\list.h:16:7: error: declaration of 'class List<T>'
Run Code Online (Sandbox Code Playgroud)

我该如何引用List?为什么声明不正确?

编辑:

现在改为:

template<class T>
template<class Function>
Run Code Online (Sandbox Code Playgroud)

我收到这些错误:

..\list.h:111:30: error: no match for 'operator++' in '++it'
..\list.h:112:18: error: no match for 'operator*' in '*it'
Run Code Online (Sandbox Code Playgroud)

引用此运算符声明(其中之一):

template<class T>
typename List<T>::Iterator& List<T>::Iterator::operator++() {
    List<T>::ConstIterator::operator++();
    return *this;
}
Run Code Online (Sandbox Code Playgroud)

为什么对于find()的每个实现,此运算符的声明必须不同?

gx_*_*gx_ 5

template<class T, class Function>
typename List<T>::Iterator List<T>::find(Function condition) const {
   ...
}
Run Code Online (Sandbox Code Playgroud)

反而

template<class T>
template<class Function>
typename List<T>::Iterator List<T>::find(Function condition) const {
   ...
}
Run Code Online (Sandbox Code Playgroud)

你必须"分开"两个template<...>(第一个用于类,第二个用于成员函数).

  • @Eitan:既然你有了新的错误,这就成了一个新问题.您可能应该为它启动一个新问题. (4认同)