名称空间搜索限定名称的规则是什么?

问题描述

有人可以在以下示例代码中解释我在名称空间搜索合格名称时看到的行为吗?有关该问题,请参阅嵌入式注释。

namespace ns1::hw
{

struct A1
{
   enum class E1
   {   
      E1_1,E1_2,};  
};

};

namespace ns1::ns2::hw
{

struct A2
{
   enum class E1
   {   
      E1_1,};  
};

};

namespace ns1::ns2::ns3::hw
{

struct A3
{
   enum class E1
   {   
      E1_1,};  
};

};

namespace ns1::ns2::ns3::ns4
{

struct A4
{
   int I1 { (int)hw::A3::E1::E1_1 }; // <--- this compiles OK
                                     // seems to search upwards in the parent namespace,// looking for the relative partially qualified
                                     // name.

   int I2 { (int)hw::A2::E1::E1_1 }; // <--- this doesn't
                                     // doesn't seem to apply the same search algorithm
                                     // beyond the immediate parent namespace.
};

};

int main()
{
   return 0;
} 

解决方法

在您的第一个摘录中:

   int I1 { (int)hw::A3::E1::E1_1 }; // <--- this compiles OK
                                     // seems to search upwards in the parent namespace,// looking for the relative partially qualified
                                     // name.
如您所料,

hw中寻找ns4。它不存在,因此在父名称空间ns3中寻找它。它在此处找到hw,然后找到嵌套名称A3,然后依次找到E1E1_1,这样名称查找就成功了。

在第二个片段中:

   int I2 { (int)hw::A2::E1::E1_1 }; // <--- this doesn't
                                     // doesn't seem to apply the same search algorithm
                                     // beyond the immediate parent namespace.

实际上应用了相同的规则。在hw中寻找ns4。它不存在,因此在ns3中寻找它。在那里找到了,但是然后找不到嵌套名称A2

现在,名称查找仅在名称空间层次结构中向上。它会根据需要找到所需的级别,但是如果它在名称空间级别内找到匹配项,则此过程将停止。如果以后再找到缺少的嵌套名称,它将不会反向运行并继续在命名空间层次结构中向上查找,相反,这只是一个硬错误。

在这种情况下,如果hw中没有ns3,则查找将转到父命名空间ns2,然后是嵌套名称A2E1E1_1将会被成功找到。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...