Discussion: Valid C++?
Afficher un message
Vieux 17/10/2007, 12h43   #3
Jonathan Lane
Aucun Avatar
 
Messages: n/a
Hébergeur:
Par défaut Re: Valid C++?

On Oct 17, 11:15 am, Boris <bo...@gtemail.net> wrote:
> Is this a valid C++ program (according to the C++ standard)? I ask as I'm
> trying to port a Windows library to Solaris, and the Solaris C++ compiler
> reports an error (The name x is ambiguous in ns1: ns2::x and ns1::x). The
> code below reproduces the problem, and I wonder now if I have to adapt the
> code or submit a bug report to Sun?
>
> namespace ns1 {
> struct x { };
>
> }
>
> namespace ns2 {
> using namespace ns1; // If this line is removed ...
> void x(); // ... or this line the code compiles.
> struct x { };
>
> }
>
> int main()
> {
> struct ns2::x x;
>
> }


Clearly the "using namespace ns1" line is going to be a problem since
you're polluting your ns2 namespace with the colliding names from ns1.
I can understand that this is going to make ns2 contain ambiguous
names.

Solutions:
rename your functions and structs so that they're unique. This also
makes the maintenance a lot easier since a developer doesn't need to
think about whether you mean function x, struct x, or alternative
struct x when they read your code.

and/or don't import the whole of ns1 into ns2. Use the fully qualified
namespace name to address ns1::x. namespaces are there to prevent this
kind of collision. By importing the whole namespace you essentially
bypass that benefit.

  Réponse avec citation
 
Page generated in 0,04728 seconds with 9 queries