tags:

views:

29

answers:

1

Hi all, I'm trying to make a pretty-printer for std::vector's of whatever ... doubles, my own custom classes... anything that has a friend std::ostream& operator<<.

However, when trying to compile the following function:

template <typename T> 
std::ostream& operator<<(std::ostream& os, std::vector<T> const& list) {
  std::vector<T>::const_iterator i = list.begin();

  if (i == list.end()) {
    os << "[ ]";
    return os;
  }

  os << "[ " << *i << "\n";

  ++i;
  for (; i != list.end(); ++i) {
    os << ", " << *i << "\n";
  }

  os << "]";
  return os;
}

The third line gives a compilation error, error: expected ';' before 'i'

I'm not really sure what's causing this, but I suspect I'm misusing templates. Any help would be appreciated!

+3  A: 

The compiler doesn't know you're trying to declare i as variable because that template expression is based on a template parameter. That's why the keyword typename is for. Try this:

  typename std::vector<T>::const_iterator i = list.begin();
eduffy