相同的函数名称在不同的命名空间中

Same function name in different namespaces

本文关键字:命名空间 函数      更新时间:2023-10-16

假设我有不同的名称空间类似于apple命名空间和orange命名空间,但这两个命名空间都包含一个名为myfunction()的函数。

当我在main()中调用myfunction()时会发生什么?

这正是引入命名空间的目的。

main()中,或者通常在全局命名空间中,您将能够选择必须调用哪个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
}

使用指令 (using namespace apple)或使用声明 (using apple::myfunction)的情况下,主程序的最后一行将调用名称空间apple中的版本。如果两个版本的myfunction都在作用域中,最后一行将再次产生错误,因为在这种情况下,您必须指定必须调用哪个函数。

考虑以下示例:

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;
}

对于声明函数的命名空间,编译器生成每个函数的唯一标识,称为Mangled Name,这只不过是定义函数的命名空间作用域、函数名称、返回类型和实际参数的编码。看到评论。当您创建对此函数的调用时,每个函数调用都会查找相同的损坏签名,如果没有找到,编译器会报告错误。

尝试使用clang -emit-llvm -S -c main.cpp -o main。