user definitions in the std namespace

J

John Harrison

Is the following code legit?

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

namespace std
{
template <class T, class U>
std::eek:stream& operator<<(std::eek:stream& 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::eek:stream_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
 
J

John Harrison

Is the following code legit?

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

namespace std
{
template <class T, class U>
std::eek:stream& operator<<(std::eek:stream& 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::eek:stream_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

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/wg21/docs/lwg-defects.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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,995
Messages
2,570,235
Members
46,821
Latest member
AleidaSchi

Latest Threads

Top