Ziffusion
Ziffusion

Reputation: 8923

What are the rules for namespace search for qualified names?

Can someone explain the behavior I am seeing for namespace search for qualified names in the following example code? See inline comments for the issue.

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

Upvotes: 1

Views: 243

Answers (1)

cigien
cigien

Reputation: 60228

In your first snippet:

   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.

as you seem to expect, hw is looked for in ns4. It doesn't exist, so it is looked for in the parent namespace ns3. It finds hw there, and then it finds the nested names A3, then E1, and then E1_1, and so the name lookup succeeds.

In the second snippet:

   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.

actually the same rules are applied. hw is looked for in ns4. It doesn't exist, so it's looked for in ns3. It's found there, but then it fails to find the nested name A2.

Now name lookup will only go upwards in a namespace hierarchy. It will go up as many levels as needed to find a name, but if it ever finds a match inside a namespace level, this process stops. If it then later finds a missing nested name, it won't go in reverse and continue looking upwards in the namespace hierarchy, it's just a hard error instead.

In this case, if there was no hw in ns3, then the lookup would have gone up to the parent namespace ns2, and then the nested names A2, E1, and E1_1 would have been found successfully.

Upvotes: 1

Related Questions