Consider the following snippet:
void Foo() // 1
{
}
namespace
{
void Foo() // 2
{
}
}
int main()
{
Foo(); // Ambiguous.
::Foo(); // Calls the Foo in the global namespace (Foo #1).
// I'm trying to call the `Foo` that's defined in the anonymous namespace (Foo #2).
}
How can I refer to something inside an anonymous namespace in this case?
You can't. The standard contains the following section (§7.3.1.1, C++03):
An unnamed-namespace-definition behaves as if it were replaced by
namespace unique { /* empty body */ }
using namespace unique;
namespace unique { namespace-body }
where all occurrences of unique in a
translation unit are replaced by the
same identifier and this identifier
differs from all other identifiers in the entire program.
Thus you have no way to refer to that unique name.
You could however technically use something like the following instead:
int i;
namespace helper {
namespace {
int i;
int j;
}
}
using namespace helper;
void f() {
j++; // works
i++; // still ambigous
::i++; // access to global namespace
helper::i++; // access to unnamed namespace
}
While Georg gives standard-complient, correct, right, and respectable answer, I'd like to offer my hacky one - use another namespace within the anonymous namespace:
#include <iostream>
using namespace std;
namespace
{
namespace inner
{
int cout = 42;
}
}
int main()
{
cout << inner::cout << endl;
return 0;
}
The only solution I can think of that doesn't modify the existing namespace arrangement is to delegate main to a function in the anonymous namespace. (main itself is required to be a global function (§3.6.1/1), so it cannot be in an anonymous namespace.)
void Foo() // 1
{
}
namespace
{
void Foo() // 2
{
}
}
namespace { // re-open same anonymous namespace
int do_main()
{
Foo(); // Calls local, anonymous namespace (Foo #2).
::Foo(); // Calls the Foo in the global namespace (Foo #1).
return 0; // return not optional
}
}
int main() {
return do_main();
}
The only real way is to put the code you want to access that namespace within the namespace itself. There's no way to resolve to the unnamed namespace otherwise, since it has no identifier you can give it to solve the ambiguous resolution problem.
If your code is inside the namespace{} block itself, the local name gets priority over the global one, so a Foo() will call the Foo() within your namespace, and a ::Foo() will call the namespace at global scope.
Just rename the local namespace function.
Related
If there are two namespaces named Foo and Bar and there is a namespace named Foo inside Bar. If I refer to a variable Foo::i from inside Bar will it search for i in both Foo and Bar::Foo. If not, is it possible to make the compiler search in both namespaces when i doesn't exist in Bar::Foo?
More concrentely in the below example, I am trying to refer variable i from namespace a in b without puting extra ::. I know putting :: works, I am trying to see if there is any other way to resolve this.
#include <iostream>
#include <string>
namespace a {
int i = 1;
}
namespace b {
namespace a {
}
namespace c {
int j = a::i; // Doesn't work, need to use ::a::i;
}
}
int main()
{
std::cout << b::c::j << "\n";
}
If you can change b::a, then you can indeed make certain declarations available in b::a from ::a as fallbacks:
namespace a {
int i = 1;
int j = 2;
}
namespace b {
namespace a {
namespace detail {
using ::a::i; // Selectively bring declarations from ::a here
}
using namespace detail; // Make the names in detail available for lookup (but not as declarations).
//int i = 2;
}
namespace c {
int j = a::i; // Uses ::a::i
// int k = a::j; // ERROR! We didn't bring ::a::j into b::a at all
}
}
Here it is live.
Un-commenting the declaration of b::a::i will change the output. Since a proper declaration takes precedence over names brought in by a namespace using directive.
You could explicitly have a using declaration in the inner namespace for variables that it wants to use from the outer one.
i.e. for your example,
namespace a {
int i = 1;
}
namespace b {
namespace a {
using ::a::i; //inner one does not define its own
int i2 = 2; //inner one creates its own variable
}
namespace c {
int j = a::i; // Doesn't work, need to use ::a::i;
}
}
See:
https://en.cppreference.com/w/cpp/language/namespace#Using-declarations
Quote from the standard:
A using-directive specifies that the names in the nominated namespace
can be used in the scope in which the using-directive appears after
the using-directive. During unqualified name lookup (3.4.1), the names
appear as if they were declared in the nearest enclosing namespace
which contains both the using-directive and the nominated namespace.
Look at this code:
namespace A {
int fn() { return 1; }
}
namespace Inner {
int fn() { return 2; }
namespace B {
using namespace A;
int z = fn();
}
}
Here, before I knew the exact rules of namespaces, I had expected that z will be initialized to 1, as I written using namespace A, so expected that A::fn() will be used. But it is not the case, z will be initialized to 2, as Inner::fn() is called because of the rule I quoted.
What is the rationale behind this behavior: "as if they were declared in the nearest enclosing namespace which contains both the using-directive and the nominated namespace"?
What would be the cons, if using namespace worked as applying using declarations for everything in that namespace?
Note: this is the related issue that motivated me to ask this question.
A desirable property of a namespace system is that of what I call incremental API compatibility. That is, if I add a symbol to a namespace, then any previously working program should keep working and mean the same thing.
Now, plain C++ with overloads is not incrementally API compatible:
int foo(long x) { return 1; }
int main()
{
foo(0);
}
Now I add the overload int foo(int x) { return 2; } and the program silently changes meaning.
Anyway, when C++ people designed the namespace system they wanted that when incrementing an external API, previously working code should not change the namespace from where the symbol is chosen. From your example, the previous working code would be something like:
namespace A {
//no fn here, yet
}
namespace Inner {
int fn() { return 2; }
namespace B {
using namespace A;
int z = fn();
}
}
And z is easily initialized to 2. Now augmenting namespace A with a symbol named fn will not change the meaning of that working code.
The opposite case does not really apply:
namespace A {
int fn() { return 1; }
}
namespace Inner {
// no fn here
namespace B {
using namespace A;
int z = fn();
}
}
Here z is initialized to 1. Of course, if I add fn to Inner it will change the meaning of the program, but Inner is not an external API: actually, when Inner was written initially, A::fn did already exist (it was being called!), so there is no excuse for being unaware of the clash.
A somewhat practical example
Imagine this C++98 program:
#include <iostream>
namespace A {
int move = 0;
void foo()
{
using namespace std;
cout << move << endl;
return 0;
}
}
int main()
{
A::foo();
return 0;
}
Now, if I compile this with C++11, everything works fine thanks to this using rule. If using namespace std worked as applying using declarations for everything in that namespace, then this program would try to print function std::move instead of A::move.
Given a namespace A. Inside is an anonymous namespace with function f and a class X, also with function f: Why do I have to specify the outer namespace A:: as a qualifier when calling anonymous f from A::X::f?
As a minimal example:
#include <iostream>
using namespace std;
namespace A {
namespace {
int f( int i ) { return i; }
}
class X {
public:
static int f() { A::f( 10 ); }
};
}
int main()
{
cout << A::X::f() << endl;
return 0;
}
Because, within the scope of X::f, the unqualified name f refers to X::f, not any other f. A name declared within a scope will hide anything with the same name in an outer scope.
Here is the test code
extern "C" {int printf(const char *, ...);}
namespace PS
{
int x = 10; // A
// some more code
namespace {
int x = 20; // B
}
// more code
}
int main()
{
printf("%d", PS::x); // prints 10
}
Is there any way to access inner(unnamed) namespace's x inside main?
I dont want to change code inside PS. Apologies if the code looks highly impractical.
P.S: I tend to use the name x quite often.
No. The only way to specify a namespace is by name, and the inner namespace has no name.
Assuming you can't rename either variable, you could reopen the inner namespace and add a differently-named accessor function or reference:
namespace PS {
namespace {
int & inner_x = x;
}
}
printf("%d", PS::inner_x);
One way is to add this code:
namespace PS
{
namespace
{
namespace access
{
int &xref = x;
}
}
}
and then you can access what you want:
std::cout << PS::access::xref << std::endl; //prints 20!
Demo : http://ideone.com/peqEs
I have two namespaces defined in the default/"root" namespace, nsA and nsB. nsA has a sub-namespace, nsA::subA. When I try referencing a function that belongs to nsB, from inside of nsA::subA, I get an error:
undefined reference to `nsA::subA::nsB::theFunctionInNsB(...)'
Any ideas?
Use global scope resolution:
::nsB::TheFunctionInNsB()
#include <stdio.h>
namespace nsB {
void foo() {
printf( "nsB::foo()\n");
}
}
namespace nsA {
void foo() {
printf( "nsA::foo()\n");
}
namespace subA {
void foo() {
printf( "nsA::subA::foo()\n");
printf( "calling nsB::foo()\n");
::nsB::foo(); // <--- calling foo() in namespace 'nsB'
}
}
}
int main()
{
nsA::subA::foo();
return 0;
}
Need more information to explain that error. The following code is fine:
#include <iostream>
namespace nsB {
void foo() { std::cout << "nsB\n";}
}
namespace nsA {
void foo() { std::cout << "nsA\n";}
namespace subA {
void foo() { std::cout << "nsA::subA\n";}
void bar() {
nsB::foo();
}
}
}
int main() {
nsA::subA::bar();
}
So, while specifying the global namespace solves your current problem, in general it is possible to refer to symbols in nsB without it. Otherwise, you'd have to write ::std::cout, ::std::string, etc, whenever you were in another namespace scope. And you don't. QED.
Specifying the global namespace is for situations where there's another nsB visible in the current scope - for instance if nsA::subA contained its own namespace or class called nsB, and you want to call ::nsbB:foo rather than nsA::subA::nsB::foo. So you'd get the error you quote if for example you have declared (but not defined) nsA::subA::nsB::theFunctionInNsB(...). Did you maybe #include the header for nsB from inside namespace subA?