No name

The following code exists:

#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 am using g ++. Is there a way to call a function from an unnamed namespace in this situation? You can call a function from the global scope using :: function, but how do you call a function from an unnamed namespace? The 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() 
+4
source share
2 answers

Is there a way to call a function from an unnamed namespace in this situation?
No, not in your case.

Anonymous / UnNamed namespaces allow you to see variables and functions inside the entire translation unit, but are not visible from the outside. Although objects in an unnamed namespace can have an external connection, they are effectively qualified by a name unique to their translation unit, and therefore can never be seen from any other translation unit.

This means that your funkcja function inside the Nameless Namespace is visible in the translation module that defines the global funkcja function. This results in two identical named functions defined in the global scope, resulting in an override error.

If funkcja was only present in your UnNamed namespace, then you could name it ::funkcja , as it would be in your global scope. In conclusion, you can call functions in the UnName namespace depending on the scope in which the UnNamed namespace is present.

+2
source

The way anonymous namespaces work is that the names declared inside them are automatically displayed in the scope as if released using namespace name_of_anonymous_namespace; .

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

+4
source

All Articles