【问题标题】:What are the rules for namespace search for qualified names?命名空间搜索限定名称的规则是什么?
【发布时间】:2021-01-24 02:45:00
【问题描述】:

有人可以解释我在以下示例代码中看到的命名空间搜索限定名称的行为吗?有关该问题,请参阅内联 cmets。

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

【问题讨论】:

    标签: c++ namespaces name-lookup


    【解决方案1】:

    在你的第一个 sn-p 中:

       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.
    

    如您所料,hwns4 中查找。它不存在,因此在父命名空间ns3 中查找。它在那里找到hw,然后找到嵌套名称A3,然后是E1,然后是E1_1,因此名称查找成功。

    在第二个sn-p中:

       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 中查找。它在那里找到,但是 然后 找不到嵌套名称 A2

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

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

    【讨论】:

    • 谢谢。我期待它更像是例如cpp 如何搜索包含文件。它在整个搜索空间中尝试一个相对路径名。它不会仅仅因为找到名称的开头部分而停止。
    • @Ziffusion 是的,名称查找规则不同。我不确定这是否有根本原因,也许这样的规则会引起歧义。至少,我认为实施起来会很痛苦。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-25
    • 1970-01-01
    • 2012-01-12
    • 2012-03-26
    相关资源
    最近更新 更多