Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unnamed namespace

There is following code:

#include <iostream>

using namespace std;

namespace
{
    int funkcja()
    {
        cout << "unnamed" << endl;
        return 0;
    }
}

int funkcja()
{
    cout << "global" << endl;
    return 0;
}

int main()
{
    ::funkcja(); //this works, it will call funkcja() from global scope
    funkcja(); //this generates an error 
    return 0;    
}

I use g++. Is there some way to call function from unnamed namespace in such situation? It is possible to call function from global scope using ::function, but how to call function from unnamed namespace? Compiler generates an error:

prog3.cpp: In function ‘int main()’:
prog3.cpp:43:17: error: call of overloaded ‘funkcja()’ is ambiguous
prog3.cpp:32:5: note: candidates are: int funkcja()
prog3.cpp:25:6: note:                 int<unnamed>::funkcja()
like image 745
scdmb Avatar asked Jun 26 '11 17:06

scdmb


1 Answers

The way that anonymous namespaces work is that the names declared inside them are automatically visible in the enclosing scope as if a using namespace name_of_anonymous_namespace; had been issued.

Because of this, in your example the name funkcja is ambiguous and un-disambiguatable [new word!]. It looks like you don't really want an anonymous namespace, you really need a properly named namespace.

like image 62
CB Bailey Avatar answered Oct 22 '22 08:10

CB Bailey