Connecting Tech Pros Worldwide Forums | Help | Site Map

user definitions in the std namespace

John Harrison
Guest
 
Posts: n/a
#1: Jul 22 '05
Is the following code legit?

#include <iostream>
#include <utility>
#include <map>
#include <algorithm>
#include <iterator>

namespace std
{
template <class T, class U>
std::ostream& operator<<(std::ostream& out, std::pair<T, U> const& p)
{
return out << p.first << ' ' << p.second;
}
}

int main()
{
std::map<int, int> m;
std::copy(m.begin(), m.end(),
std::ostream_iterator<std::map<int, int>::value_type>(std::cout));
}

No less than three compilers accept this (VC++ 7.1, g++ 3.3.1 and online
Comeau C++) but it seems that the standard doesn't like it, 17.4.3.1 para
1 allows template specialisations to be added to std, but not it seems
function overloads.

The same three compilers do not accept the same code but with operator<<
defined in the global namespace. All three give variations on 'no suitable
operator<< found' error messages.

So it is possible to define operator<< for a type in the std namespace. If
so how to do it?

John

John Harrison
Guest
 
Posts: n/a
#2: Jul 22 '05

re: user definitions in the std namespace


On Thu, 22 Jul 2004 20:17:00 +0100, John Harrison
<john_andronicus@hotmail.com> wrote:
[color=blue]
> Is the following code legit?
>
> #include <iostream>
> #include <utility>
> #include <map>
> #include <algorithm>
> #include <iterator>
>
> namespace std
> {
> template <class T, class U>
> std::ostream& operator<<(std::ostream& out, std::pair<T, U> const& p)
> {
> return out << p.first << ' ' << p.second;
> }
> }
>
> int main()
> {
> std::map<int, int> m;
> std::copy(m.begin(), m.end(),
> std::ostream_iterator<std::map<int, int>::value_type>(std::cout));
> }
>
> No less than three compilers accept this (VC++ 7.1, g++ 3.3.1 and online
> Comeau C++) but it seems that the standard doesn't like it, 17.4.3.1
> para 1 allows template specialisations to be added to std, but not it
> seems function overloads.
>
> The same three compilers do not accept the same code but with operator<<
> defined in the global namespace. All three give variations on 'no
> suitable operator<< found' error messages.
>
> So it is possible to define operator<< for a type in the std namespace.
> If so how to do it?
>
> John[/color]

Answering my own question here but in case anyone is interested I found
this reference from the defect reports.

http://www.open-std.org/jtc1/sc22/wg...fects.html#226

The note starting "J. C. van Winkel points out ..." directly addresses
this issue but without deciding whether it is an issue let alone proposing
a resolution.

john
Closed Thread