不同命名空间中的相同函数名称
假设我有不同的命名空间 ,如apple命名空间和橙色命名空间,但两个命名空间都包含一个名为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;
}
按照其功能声明命名空间,编译器会生成一个名为重整名称每个函数,它只不过是名字空间范围的编码,其中定义函数,函数名,返回类型和实际参数的唯一标识。看评论。在您创建对此函数的调用时,每个函数调用都会查找相同的受到破坏的签名,如果找不到,则编译器会报告错误。
尝试使用clang -emit-llvm -S -c main.cpp -o main.ll进行实验,如果您对内部工作感兴趣。
请注意,标准没有指定任何名称混搭风格,也没有实际提及它,据我所知。你的例子对于G ++来说是正确的,但MSVC的做法是不同的,我想英特尔会以另一种方式来做。用例子举例说明是很好的,但是应该清楚,当这些例子不是可移植的,也不是标准的时候,你不能依赖这种行为,因为它是由实现定义的。 – Elkvis
是的。埃尔维斯谢谢指出。范围映射是实现定义的,并随编译器而变化。例子是说明作用域内的作用域和函数是如何相互关联的。当然,** NameLookUp **算法的变化,可能是简单的表格!但最终我们正在寻找似乎具有相同名称的功能。并且很容易通过clang学习这个概念,因此最后提示:) –
完全是OT,但是不应该“Soron”是“Sauron”? –
很可能找不到该名称,代码将无法编译。但可能会发布一些示例代码,因为细节很重要。 – juanchopanza
使用您想要的名称空间限定函数调用,即apply :: myfunction()或orange :: myfunction() – acraig5075