Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ use symbols from other namespace without making them externally accessible

Tags:

c++

Is there a construction similar to using namespace that doesn't make the imported symbols visible outside the body (or bodies) of the namespace?

In this example here, every symbol in whatever and other_namespace will be accessible through Foo::<name_of_symbol> as well ... and I'd like a way to prevent that from happening.

namespace Foo {
  using namespace whatever;
  using namespace other_namespace;
  // some definitions
}

As a complete example, this program is valid. If an alternative to using namespace with the intended semantics existed and were used, it would not be.

namespace a {
  int func(int x) {
    return 10;
  }
}

namespace b {
  using namespace a;
}

namespace c {
  int do_thing(int x) {
    return b::func(57);
  }
}
like image 277
Gregory Nisbet Avatar asked Aug 18 '17 05:08

Gregory Nisbet


People also ask

Which operator is used to access a namespace member from outside of its namespace?

Use :: for classes and namespaces A scope resolution operator without a scope qualifier refers to the global namespace. You can use the scope resolution operator to identify a member of a namespace , or to identify a namespace that nominates the member's namespace in a using directive.

Are namespace members visible outside their namespace?

All code in the same file can see the identifiers in an unnamed namespace but the identifiers, along with the namespace itself, are not visible outside that file—or more precisely outside the translation unit.

What happens if you remove using namespace std from your code?

Thus, removing using namespace std; changes the meaning of those unqualified names, rather than just making the code fail to compile. These might be names from your code; or perhaps they are C library functions.

Can you use two namespaces C++?

You can have the same name defined in two different namespaces, but if that is true, then you can only use one of those namespaces at a time. However, this does not mean you cannot use the two namespace in the same program. You can use them each at different times in the same program.


1 Answers

You can use an alias inside an unnamed namespace.

namespace a_long_namespace_name {
    void someFunc() {};
}

namespace b {
    namespace { // an unnamed namespace
        namespace a = a_long_namespace_name; // create a short alias
    }

    void someOtherFunc() {
        a::someFunc();
    }
}

b::a::someFunc(); // compiler error

You would still need to be writing the namespace to call a function, but it makes calls way shorter.

like image 107
muXXmit2X Avatar answered Oct 07 '22 15:10

muXXmit2X