mercredi 12 juillet 2017

writing template for operator<< for any vector

I'm trying to write a template operator for any iterable container. Getting a strange error:

#include <iostream>

template <typename C>
std::ostream& operator<<(std::ostream& os, const C& c) {
  os << "[";
  for (const auto& v : c) {
    os << v << " ";
  }
  os << "]";
  return os;
}

vec.cc:5:6: error: use of overloaded operator '<<' is ambiguous (with operand types 'std::ostream' (aka 'basic_ostream') and 'const char [2]') os << "["; ~~ ^ ~~~

Why this error? And how do I achieve what I want?

Aucun commentaire:

Enregistrer un commentaire