Best way to specialise operator<< for std::ostream and std::vector with generic template functions?

前端 未结 2 1664
广开言路
广开言路 2021-01-03 03:35

I am having trouble with the two-phase look-up as specified by the standard and (correctly) implemented by clang in connection with an overload of operator<<

2条回答
  •  执笔经年
    2021-01-03 04:06

    Don't overload operators for types you don't control, such as:

    std::ostream& operator<<(std::ostream& s, std::vector const& v);
    

    Instead create a tiny adaptor class and define the operator for that, for example:

    template struct PrintableVector {
      std::vector const* vec;
    }
    
    template
    std::ostream& operator<<(std::ostream& s, PrintableVector v) {
      for(auto const& elem : *v.vec) { s << elem << ", "; }
      return s;
    }
    

    That can be used like:

    shift(std::cout, PrintableVector{&v});
    

    You can put the adaptor in whatever namespace you like, and put the overloaded operator in the same namespace so it can be found by ADL.

    That avoids lookup problems, doesn't require adding anything to namespace std, and doesn't try to uniquely define what it means to print a vector (which might cause problems in other parts of the program if some other code assumes vectors are not printable, or tries to define its own overloads for them).

提交回复
热议问题