4

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?

Cookie
  • 12,004
  • 13
  • 54
  • 83
  • 2
    Could you add an example situation where it fails ? I don't see why that would happen if you declared it in the global namespace. – Quentin May 03 '16 at 09:36
  • 1
    [Here is what I understood](http://coliru.stacked-crooked.com/a/49e0578fef688e87), and works. – Quentin May 03 '16 at 09:50
  • 3
    You might be interested in something like the [pretty printer](https://stackoverflow.com/questions/4850473/pretty-print-c-stl-containers). – Kerrek SB May 03 '16 at 09:53
  • 1
    @Quentin I don't know if this is what OP is talking about, but if you have a specialized `operator<<` in your namespace before the call to the templated `operator<<`, it will hide the templated version for vector (http://coliru.stacked-crooked.com/a/887519cabec80214). – Holt May 03 '16 at 09:59
  • @Holt good catch. I don't think there is any way around importing `::operator<<` back into the overload set though. – Quentin May 03 '16 at 10:01
  • @Quentin: I modified your example to exemplify the problem: http://coliru.stacked-crooked.com/a/9b5899bf480da83e – Cookie May 04 '16 at 06:51
  • @KerrekSB: Thanks for the link, but unless I am misunderstanding they are simply going ahead and placing some stuff into the `std` namespace... – Cookie May 04 '16 at 06:53
  • @Cookie: Yes, that's a problem. I don't think you can provide an overload completely unintrusively for something like `std::vector`. But how about requiring just a single line like `using namespace operators;`, and you stick all the using declarations into that namespace? That way users could opt in easily, but it'd still be explicit. – Kerrek SB May 04 '16 at 07:54

0 Answers0