Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there analog of ".." for c++ namespaces?

Tags:

c++

namespaces

Hello I have the following structure in my code:

namespace ns
{
class A
{
  public:
    class Impl
    {
        public: static int x;
    };
    class B
    {
      public:
        class Impl
        {
          public:
            Impl(){printf("%d", ns::A::Impl::x);}
        };
    };
};
}

Is there a way to access that x property, using a relative, not the absolute path?

It would be more convenient, because, someday I could change the namespace name from ns to e.g. other, or put this entire file into some outer namespace.

like image 576
Necto Avatar asked Dec 13 '25 17:12

Necto


2 Answers

Is there a way to access that x property, using a relative, not the absolute path?

Symbols from the enclosing scope/namespace are accessible in the current scope/namespace.

ns::A::Impl::x could be shortened to A::Impl::x (can't omit A:: because you have two Impl).

like image 82
Maxim Egorushkin Avatar answered Dec 15 '25 06:12

Maxim Egorushkin


There isn't an equivalent of "..", i.e. a way to specify "the enclosing namespace/class", but you can manually implement a similar thing:

class B
{
    typedef A parent;          // <---- add this

// ...

    printf("%d", parent::Impl::x);

In this particular situation it doesn't gain anything: this is just a more roundabout way of having A::Impl::x as Maxim suggested. But in general, if you have a more complicated hierarchy then this form may gain you some readability.

like image 40
M.M Avatar answered Dec 15 '25 07:12

M.M



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!