tags:

views:

99

answers:

3

I am confused what to do when having nested namespaces and declaration of objects.

I am porting some code that links against a static library that has a few name spaces.

Example of what I am talking about:

namespace ABC {

    namespace XYZ {

        //STUFF
    }
}

In code what so I do to declare an object that is in namespace XYZ?

if I try:

XYZ::ClassA myobject;

or:

ABC::XYZ::ClassA myobject;

or:

ABC::ClassA myobject;

I get does not name a type errors, even though ClassA definitely exists.

What is proper here?

+4  A: 

The correct method is ABC::XYZ::ClassA. If that's not working, the problem is something else.

GMan
+5  A: 

It depends on the namespace you already are:

If you're in no namespace or another, unrelated namespace, then you have to specify to whole path ABC::XYZ::ClassA.

If you're in ABC you can skip the ABC and just write XYZ::ClassA.

Also, worth mentionning that if you want to refer to a function which is not in a namespace (or the "root" namespace), you can prefix it by :::

Example:

int foo() { return 1; }

namespace ABC
{
  double foo() { return 2.0; }

  void bar()
  {
    foo(); //calls the double version
    ::foo(); //calls the int version
  }


}
ereOn
A: 

If myobject is declared in that namespace and you want to declare it again (for defining it), you do it by prefixing its name, not its type.

ClassA ABC::XYZ::myobject;

If its type is declared in that namespace too, you also need to prefix the name of the type

ABC::XYZ::ClassA ABC::XYZ::myobject;

It's rarely needed to redeclare an object like that. Often the first declaration of an object is also its definition. If you want to first declare the object, you have to do it in that namespace. The following declares and defines "myobject"

namespace ABC {
  namespace XYZ {
    ClassA myobject;
  }
}

If you have defined in object like this, you refer to it by saying ABC::XYZ. You don't have to "declare" that object somehow in order to use it locally

void f() {
  ABC::XYZ::myobject = someValue;

  // you *can* however use a using-declaration
  using ABC::XYZ::myobject;
  myobject = someValue;
}
Johannes Schaub - litb