FranzFerdi
FranzFerdi

Reputation: 13

(c++)can u nest namespaces from extern sources

i have a few headers with namespaces which all follow a certain namepattern

right now they all have a prefix infront of their actual name such as

namespace Xname{//inside name.h
  //stuff here
};
namespace Xsomething{//inside something.h
  //stuff here
};

now this works pretty good for my usage atm, but my idea is to create one more header that contains a namespace that would collect all the other namespaces so i can access them like so:

#include "mainheader.h"
X::name::stuff
X::something::stuff

this way i would just change the namespace name for new headers in the future like so

X::name::stuff
hello::name::stuff

i cant nest them like this:

namespace x{
   namespace something{
     //stuff
   }
}

Upvotes: 1

Views: 50

Answers (2)

Lasersköld
Lasersköld

Reputation: 2225

You could define the new namespaces inside each other like so

#include <iostream>

namespace Xname{//inside name.h
  const int x = 0;
};
namespace Xsomething{//inside something.h
  const int y = 1;
};

// Your other header
namespace X {
namespace name = Xname;
namespace something = Xsomething;
}

int main() {
  std::cout << X::name::x << "\n";
  std::cout << X::something::y << "\n";
}

Upvotes: 1

Marius Bancila
Marius Bancila

Reputation: 16328

If I understand you correctly, you can use the using namespace directive for this. Here is an example:

namespace Xname {
    struct foo {};
}

namespace X {
    namespace name {
        using namespace Xname;
    }
}

int main()
{
    Xname::foo f1;       // original
    
    X::name::foo f2;     // alternative
}

Upvotes: 0

Related Questions