如何为std :: list< *>写一个漂亮的打印机在C ++中?

时间:2015-06-20 09:20:52

标签: c++ templates stl pretty-print generic-programming

我可以轻松地为std :: vector< *>写一个漂亮的打印机像这样:

template <typename T>
std::ostream &operator<<(std::ostream &origin, const std::vector<T> &vec){
    origin << "{ ";
    for(int i = 0; i < vec.size(); i++)
        origin << vec[i] << " ";
    origin << "}";
    return origin;
}

但是当我为std :: list&lt; *&gt;写了一台漂亮的打印机时类似地:

template <typename T>
std::ostream &operator<<(std::ostream &origin, const std::list<T> &lis){
    origin << "[ ";
    for(std::list<T>::const_iterator it = lis.begin(); it != lis.end(); it++)
        origin << *it << " ";
    origin << "]";
    return origin;
}

gcc报道:

../main.cpp: In function ‘std::ostream& operator<<(std::ostream&, const std::list<T>&)’:
../main.cpp:13:6: error: need ‘typename’ before ‘std::list<T>::const_iterator’ because ‘std::list<T>’ is a dependent scope
  for(std::list<T>::const_iterator it = lis.begin(); it != lis.end(); it++)
      ^
../main.cpp:13:35: error: expected ‘;’ before ‘it’
  for(std::list<T>::const_iterator it = lis.begin(); it != lis.end(); it++)
                                   ^
../main.cpp:13:53: error: ‘it’ was not declared in this scope
  for(std::list<T>::const_iterator it = lis.begin(); it != lis.end(); it++)
                                                     ^
../main.cpp: In instantiation of ‘std::ostream& operator<<(std::ostream&, const std::list<T>&) [with T = int; std::ostream = std::basic_ostream<char>]’:
../main.cpp:24:15:   required from here
../main.cpp:13:51: error: dependent-name ‘std::list<T>::const_iterator’ is parsed as a non-type, but instantiation yields a type
  for(std::list<T>::const_iterator it = lis.begin(); it != lis.end(); it++)
                                                   ^
../main.cpp:13:51: note: say ‘typename std::list<T>::const_iterator’ if a type is meant
make: *** [main.o] Error 1

你能帮我为std :: list&lt; *&gt;写一个漂亮的打印机吗?并向我解释错误信息的含义吗?

0 个答案:

没有答案