Re: operator<< for std::map
In article <MPG.2191a49a123c9be0989a62@news.sunsite.dk>, Jerry Coffin
<jcoffin@taeus.com> wrote:
In article <301020071953392527%cbarron413@adelphia.net>, cbarron413
@adelphia.net says...
[ ... ]
Ok, I learn something, thanks, It works with user types in a
different namespace,including the global namespace. Stiil a problem
with built in types like std::pair<int,int> however.
std::pair<int, int> is a user-defined type, not a built-in type. Even
though the template for pair is present in the library, each
instantiation of a template is a type, and this type isn't built-in.
OTOH, this type still isn't associated with any particular namespace, so
the fact that it's not built-in has little effect on ADL.
Well this may be more expressive:
//code begins
#include <vector>
#include <utility>
#include <algorithm>
#include <iterator>
#include <iostream>
//#define USE_NAMESPACE_ MY
//#define USE_PLAIN_PAIR
#ifdef USE_NAMESPAACE_MY
namespace My
{
#define CREATE My::create
#else
#define CREATE create
#endif
struct foo
{
int x;
foo(int y):x(y){}
};
std::ostream & operator << (std::ostream &os,const foo &f)
{
return os << f.x;
}
std::ostream & operator << (std::ostream &os,const
std::pair<foo,foo> &p)
{
return os << '(' << p.first << ',' << p.second << ')';
}
struct create
{
int i;
create():i(0){}
std::pair<foo,foo> operator ()()
{
return std::pair<foo,foo>(i++,10*i); // FRAGILE but ok for a
test:)
}
};
#ifdef USE_NAMESPACE_MY
}
#endif
std::ostream & operator << (std::ostream &os,const std::pair<int,int>
&p)
{
return os << '(' << p.first << ',' << p.second << ')';
}
int main()
{
#ifdef FOO
typedef My::foo foo;
#endif
std::vector<std::pair<foo,foo> > items;
std::generate_n(std::back_inserter(items),20,CREATE());
std::copy(items.begin(),items.end(),std::ostream_iterator<std::pair<foo,
foo> >(std::cout,"\n"));
#ifdef USE_PLAIN_PAIR
std::vector<std::pair<int,int> > t2;
std::fill_n(std::back_inserter(t2),10,std::pair<int,int>(0,10));
std::copy(t2.begin(),t2.end(),std::ostream_iterator<std::pair<int,int>
(std::cout,"\n"));
#endif
std::cout << "done\n";
}
//code ends
by defining and undefining USE_NAME_SPACE_MY and/or USE_PLAIN_PAIR
and cw 9.4 yields
USE_PLAIN_PAIR is defined - does not compile can't find op << in
std::ostream_iterator
USE_PLAIN_PAIR is not defined - compiles and runs whether
USE_NAMESPACE_MY is definde or not.
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]