Re: friend operator << overload ambiguity error

From: Dave Moore (dtmoore_at_email.unc.edu)
Date: 01/18/05


Date: Tue, 18 Jan 2005 17:16:36 +0100


"Jerry Coffin" <jcoffin@taeus.com> wrote in message
news:1105981522.835449.237100@c13g2000cwb.googlegroups.com...
> [ ... ]
>
> > > class Thing;
> > > namespace std {
> >
> > This is a big no-no ... we users are not allowed to "pollute" the std
> > namespace. That is the whole point of calling it std, meaning
> standard. As
> > soon as you start adding names to it, it will behave differently for
> you
> > than for the rest of the world, and so it is then by definition not
> standard
> > anymore.
>
> This isn't entirely true -- the standard gives explicit permission for
> users to add names to namespace std under the right circumstances. I
> don't have my copy of the standard here at work to give all the
> details, but if memory serves, overloading on a UDF fulfills one of the
> major requirements.
>

You are absolutely right .. I have heard the wisdom espoused in my earlier
"preachy" post so many times that I just regurgitated it without checking.
This is what the Standard has to say about what can and cannot be added to
namespace std (17.4.3.1/1):

"It is undefined for a C++ program to add declarations or definitions to
namespace std or namespaces within namespace std unless otherwise specified.
A program may add template specializations for any standard library template
to namespace std. Such a specialization (complete or partial) of a standard
library template results in undefined behavior unless the declaration
depends on a user-defined name of external linkage and unless the
specialization meets the standard library requirements for the original
template."

The OP's declaration is for a new template function, not a specialization,
so it does not meet the criteria described above. I also checked out the
section on output streams (27.6.2), where basic_ostream is defined, and I
didn't see any further relaxation of the "user cannot inject names into std
namespace" restriction. Thus it seems he is "not allowed" to put his
declaration in std after all.

So, although my general statement was inaccurate, I think the overall
sentiment was on the mark. A relevant question to the OP is also why he
thought he needed to put his operator<< in std anyway .. I have lots of
similar definitions, and they are all in my own namespaces (and very
occasionally in the global namespace).

Hope this clears things up ...

Dave Moore
<gives self "two for preaching" .... *smack* ... *smack* >



Relevant Pages