I seem to recall seeing notes somewhere on a way to combine multiple namespaces into one.
Now, looking for said notes I am not finding them -- even searching using search terms combing, grouping, merging and wrapping I'm not coming up with anything. Maybe I misunderstood what I saw before. I don't have a specific application for this, it's just a curiosity and it's a bit contrived.
But, starting with two name spaces...
namespace a {int func() {return 1;}}
namespace b {int func() {return 2;}}
I was looking for syntax to either simply wrap them in another name -- after the fact -- (yes, I know I can rewrite it in a nested way) or merge them into one new space. But, I did find that I if I add to one of the namespaces that much works.
namespace c {namespace a{ int func2() {return 3;}} }
int main(int argc, char **argv)
{
int a = a::func(); // normal case
int c = c::a::func2(); // wrapped and added to
//int c = c::func2(); // doesn't work
//int d = a::func2(); // doesn't work
}
The question are:
1) is there syntax that just combines the two spaces into one new one?
2) is there a syntax to wrap the spaces without adding more to the subspaces?
You can do this:
namespace c
{
using namespace a;
using namespace b;
}
But if a and b have elements with the same names, you won't be able to use them from namespace c.
The best solution since C++11 is:
namespace c
{
inline namespace a { using namespace ::a; }
inline namespace b { using namespace ::b; }
}
This way for names that not conflict you can qualify only by c
and you can resolve conflicts by qualifing c::a
or c::b
.
e.g.:
namespace a
{
auto foo_a() { cout << "a::foo_a" << endl; }
auto foo() { cout << "a::foo" << endl; }
}
namespace b
{
auto foo_b() { cout << "b::foo_b" << endl; }
auto foo() { cout << "b::foo" << endl; }
}
namespace c
{
inline namespace a { using namespace ::a; }
inline namespace b { using namespace ::b; }
}
int main()
{
c::foo_a();
c::foo_b();
c::a::foo();
c::b::foo();
return 0;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With