【问题标题】:C++ functors and templates: error: declaration of 'class List<T>'C++ 仿函数和模板:错误:'class List<T>' 的声明
【发布时间】:2013-06-14 09:15:12
【问题描述】:

我在一个名为 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;
}

错误是:

..\list.h:108:62: error: invalid use of incomplete type 'class List<T>'
..\list.h:16:7: error: declaration of 'class List<T>'

我应该如何引用列表?为什么声明不正确?

编辑:

现在改为:

template<class T>
template<class Function>

我收到以下错误:

..\list.h:111:30: error: no match for 'operator++' in '++it'
..\list.h:112:18: error: no match for 'operator*' in '*it'

引用此操作符声明(其中之一):

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

为什么这个操作符的声明对于 find() 的每个实现都必须不同?

【问题讨论】:

    标签: c++ templates c++11 nested functor


    【解决方案1】:

    没有

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

    而是

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

    您必须将两个template&lt;...&gt;“分开”(第一个用于类,第二个用于成员函数)。

    【讨论】:

    • @Eitan 也许这不能解决你的新错误,但你在函数内部使用List&lt;int&gt;::Iterator 而不是List&lt;T&gt;::Iterator
    • @Eitan:现在你有一个新错误,这成为一个新问题。您可能应该为此提出一个新问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-07-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多