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

What are the rules for namespace search for qualified names?

有人可以解释我在以下示例代码中看到的命名空间搜索限定名称的行为吗?查看问题的内联评论。

namespace ns1::hw
{

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

};

namespace ns1::ns2::hw
{

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

};

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

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

};

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.

如您所料,在 ns4 中查找 hw。它不存在,因此在父命名空间 ns3 中查找。它在那里找到 hw,然后找到嵌套的名称 A3,然后是 E1,然后是 E1_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.

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

现在名称查找只会在名称空间层次结构中向上查找。它会根据需要上升多个级别来查找名称,但如果它在名称空间级别内找到匹配项,则此过程将停止。如果稍后发现缺少的嵌套名称,它不会反向继续在命名空间层次结构中向上查找,而是一个硬错误。

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