开发者

"Expected ; before..." with template function to print std::vector<Whatever>

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开发者_如何学Go) {
    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!


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();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜