We have dozens of string-like classes spread across dozens of namespaces, but they each have a similar structure:
namespace N::N1 {
struct S1 {
std::string_view sv() const;
};
}
We'd like to write a template operator<< to insert these into ostreams, something like
template<typename T>
requires requires(const T& t) {
{ t.sv() } -> std::same_as<std::string_view>;
}
std::ostream& operator<<(std::ostream& os, const T& t) {
os << t.sv();
return os;
}
In order for this function template to be found by ADL, it has to either be in std:: or a copy in each of the dozens of N::N1 namespaces. I can't put it in namespace N as ADL only looks at the innermost enclosing namespace.
Is it legal to add this function template to std:: namespace? cppreference is not clear (to me) on this point. The compilers I've tried all seem to do the right thing in any case.
(C++20 if it matters)
operator<<in global?stdwill give undefined behaviour. No diagnostic is required for undefined behaviour, so compilers may well accept it - but the behaviour of your program will then be undefined (informally, any outcome is permitted, whether the outcome seems "right" to you or not).concept SvType = requires...; template <SvType T> struct Printer { const T& m; friend std::ostream& operator<<.... };if only this form is an option:std::cout << N::Printer{s1}