Same function name in different namespaces

Suppose I have different namespaces like the Apple namespace and the orange namespace, but both namespaces contain the myfunction () function.

What happens when I call myfunction () in main ()?

+8
c ++
source share
2 answers

This is exactly what namespaces were introduced for.

In your main() or in the global namespace in general, you can choose the type that should be called by myfunctions :

 int main() { apple::myfunction(); // call the version into the apple namespace orange::myfunction(); // call the orange one myfunction(); // error: there is no using declaration / directive } 

In the case of using a directive ( using namespace apple ) or a declaration using ( using apple::myfunction ), the last line of main would call the version inside the apple namespace. If both versions of myfunction were in scope, the last line will myfunction error, because in this case you will need to specify which function to call.

+22
source share

Consider the following example.

 namespace Gandalf{ namespace Frodo{ bool static hasMyPrecious(){ // _ZN7Gandalf5FrodoL13hasMyPreciousEv return true; } }; bool static hasMyPrecious(){ // _ZN7GandalfL13hasMyPreciousEv return true; } }; namespace Sauron{ bool static hasMyPrecious(){ // _ZN5SauronL13hasMyPreciousEv return true; } }; bool hasMyPrecious(){ // _Z13hasMyPreciousv return true; } int main() { if( Gandalf::Frodo::hasMyPrecious() || // _ZN7Gandalf5FrodoL13hasMyPreciousEv Gandalf::hasMyPrecious() || // _ZN7GandalfL13hasMyPreciousEv Sauron::hasMyPrecious() || // _ZN5SauronL13hasMyPreciousEv hasMyPrecious()) // _Z13hasMyPreciousv return 0; return 1; } 

In accordance with the namespace in which the function is declared, the compiler generates a unique name for each Mangled Name function, which is nothing but the encoding of the namespace area in which the function is defined, the function name, return type, and actual parameters. see comments. When you create calls for these functions, each function call searches for the same chained signature if no compiler error is found.

Try experimenting with clang -emit-llvm -S -c main.cpp -o main.ll if you are interested in working internally.

+5
source share

All Articles