Click to See Complete Forum and Search --> : namespace confusion


GNiewerth
May 8th, 2008, 05:45 AM
Hi everyone,

Iīve got some namespace problems I donīt really understand. Iīve got a header and an implementation file where three functions reside.

test.h

#ifndef TestH
#define TestH

namespace A {
namespace B {
namespace C {

int get_x();
int get_y();
int get_z();

};
};
};
#endif


test.cpp, working version

#include "test.h"

int A::B::C::get_x()
{
return 0;
}

int A::B::C::get_y()
{
return get_x() +1;
}

int A::B::C::get_z()
{
return get_y() +2;
}


test.cpp version 2, not working.

#include "test.h"

using namespace A::B::C;

int get_x()
{
return 0;
}

int get_y()
{
return get_x() +1;
}

int get_z()
{
return get_y() +2;
}


Hereīs the calling code

#include "test.h"

int main()
{
int x = A::B::C::get_x();
int y = A::B::C::get_y();
int z = A::B::C::get_y();
}



My compiler (Borland C++ Builder 6) yields two error messages:
(1) ambiguity between A::B::C::get_x() and get_x()
(2) ambiguity between A::B::C::get_y() and get_y()

Now I have a couple of questions:

1) There are no functions get_x() and get_y() in the global namespace, so why is there an ambiguity?
2) Do I have to fully qualify the function name in my implementation file or does something exists that saves me from the extra typing?

JohnW@Wessex
May 8th, 2008, 05:54 AM
1) There are no functions get_x() and get_y() in the global namespace,Yes there are.int get_x()
{
return 0;
}

int get_y()
{
return get_x() +1;
}

int get_z()
{
return get_y() +2;
} Do I have to fully qualify the function name in my implementation fileEither that or do the following...
namespace A {
namespace B {
namespace C {

int get_x()
{
return 0;
}

int get_y()
{
return get_x() +1;
}

int get_z()
{
return get_y() +2;
}

}
}
}

GNiewerth
May 8th, 2008, 05:57 AM
Very useful, thank you. For some reasons I was convinced that the using directive tells the compiler where to put the function code, but it seems I was wrong.

treuss
May 8th, 2008, 06:05 AM
Very useful, thank you. For some reasons I was convinced that the using directive tells the compiler where to put the function code, but it seems I was wrong.What if you had more than one using directive at the beginning of your code? ;-)

Graham
May 8th, 2008, 06:37 AM
Think of it this way: it's a using directive, not a defining directive - it works when you want to use a member, but not when you want to define a member.

exterminator
May 8th, 2008, 10:01 AM
You can do something like this though:

//test.h
namespace A
{
namespace B
{
namespace C
{
void f();
}
}
}

//test.cpp
namespace ABC = A::B::C;
void ABC::f(){}
to save the typing. Hope it works.