mardi 3 mai 2016

Overloading operator << for standard containers

I'd like to be able to write << name for stl standard containers like vector, map etc, so I added to my include header definitions for operator <<, e.g.

template <class T>
inline std::ostream& operator <<(std::ostream& ss, std::vector<T> const& vec)
{
    auto it(begin(vec));
    if (it != end(vec))
        ss << *(it++);
    for (; it != end(vec); ++it)
        ss << " " << *it;
    return ss;
}

or std::copy(cont.begin(), cont.end(), std::ostream_iterator<Type>(std::cout, " "));

However, to use them, I always have to write using ::operator<<; as the operators aren't found.

As I use various namespaces, I can't just add them to all namespaces.

Ideally, I'd like to add them to std, which seems to work fine with visual studio, but then according to the standard this is undefined behavior.

Is this unofficially supported even though it isn't standard? Is there a better way to make them available without having to write using ::operator<<; everywhere and without knowing the namespace it is going to be used in in advance?

Aucun commentaire:

Enregistrer un commentaire