-2

下面是我的代码的精简版本,它给了我一个编译器错误。编译器告诉我将 typename 放在 'std::deque::reverse_iterator' 前面,这是有道理的。但如果我这样做,我会在底部收到错误。这是什么意思?如何解决?

#include <iostream>
#include <deque>

template<class T>
class Stack{

    public:
        Stack(){}
        ~Stack(){}
        void push(T c) { s.push_back(c); }
        void inspect() const{
            for(typename std::deque<T>::reverse_iterator i=s.rbegin(); i!=s.rend(); i++)
                std::cout << *i << std::endl;
        }

    private:
        typename std::deque<T> s;
};


int main(){

  Stack<int> s;
  s.push(1);
  s.inspect();
  return 0;
}

错误:

error: no matching function for call to 'std::_Deque_iterator<int, int&, int*>::_Deque_iterator(std::reverse_iterator<std::_Deque_iterator<int, const int&, const int*> >::iterator_type)'|
note: candidates are:|
note: std::_Deque_iterator<_Tp, _Ref, _Ptr>::_Deque_iterator(const iterator&) [with _Tp = int; _Ref = int&; _Ptr = int*; std::_Deque_iterator<_Tp, _Ref, _Ptr>::iterator = std::_Deque_iterator<int, int&, int*>]|
note:   no known conversion for argument 1 from 'std::reverse_iterator<std::_Deque_iterator<int, const int&, const int*> >::iterator_type {aka std::_Deque_iterator<int, const int&, const int*>}' to 'const iterator& {aka const std::_Deque_iterator<int, int&, int*>&}'|
note: std::_Deque_iterator<_Tp, _Ref, _Ptr>::_Deque_iterator() [with _Tp = int; _Ref = int&; _Ptr = int*]|
note:   candidate expects 0 arguments, 1 provided|
note: std::_Deque_iterator<_Tp, _Ref, _Ptr>::_Deque_iterator(_Tp*, std::_Deque_iterator<_Tp, _Ref, _Ptr>::_Map_pointer) [with _Tp = int; _Ref = int&; _Ptr = int*; std::_Deque_iterator<_Tp, _Ref, _Ptr>::_Map_pointer = int**]|
note:   candidate expects 2 arguments, 1 provided|
4

2 回答 2

3

没有什么依赖于std::deque<T>,所以不能有typename。只有::左边依赖于模板参数的右边的东西是依赖的。

于 2013-10-17T20:15:38.017 回答
1

这是一个很好的例子,说明 usingauto不仅可以帮助您节省打字。你在一个const成员函数中,但试图使用你的数据成员reverse_iterator,而不是const_reverse_iterator.

更改typename std::deque<T>::reverse_iteratortypename std::deque<T>::const_reverse_iterator,或更简单地说,auto

typename这是对您的数据成员的额外补充。

于 2013-10-17T20:19:58.537 回答