Item 31. Name Lookup and the interface principle Part 1

Source: Internet
Author: User

Difficulty: 9 bytes

When you call a function, which function do you call? The answer is determined by Name Lookup, But you're almost certain to find some of the details surprising.

In the following code, which functions are called? Why? Analyze the implications.

namespace A {  struct X;  struct Y;  void f( int );  void g( X );}namespace B{  void f( int i )  {    f( i );   // which f()?  }  void g( A::X x )  {    g( x );   // which g()?  }  void h( A::Y y )  {    h( y );   // which h()?  }}

 

I l @ ve ruboard

Solution

Two of the three cases are (fairly) obvious, but the third requires a good knowledge of C ++'s Name Lookup rules limit n participant ular, Koenig lookup.

Let's start simple.

namespace A {  struct X;  struct Y;  void f( int );  void g( X );}namespace B{  void f( int i )  {    f( i );   // which f()?  }

ThisF ()Callitself, with infinite recursion. The reason is that the only visibleF ()IsB: F ()Itself.

There is another function with signatureF (INT), Namely the one in namespaceA. IfBHad written"Using namespace;"Or"Using a: F;", ThenA: F (INT)Wocould have been visible as a candidate when looking upF (INT), AndF (I)Call wowould have been ambiguousA: F (INT)AndB: F (INT). SinceBDid not bringA: F (INT)Into scope, however, onlyB: F (INT)Can be considered, so the call unambiguously resolvesB: F (INT).

And now for a twist:

void g( A::X x ) {  g( x );   // which g()?}

This call is ambiguousA: G (x)AndB: G (x). The programmer must explicitly qualify the call with the appropriate namespace name to getG ()He wants.

You may at first wonder why this shoshould be so. After all, asF (),BHasn' t written"Using"Anywhere to bringA: G (x)Into its scope, so you 'd think that onlyB: G (x)Wocould be visible, right? Well, this wocould be true when T for an extra rule that C ++ uses when looking up names:

 

Koenig Lookup[1] (simplified): If you supply a function argument of class type (hereX, Of TypeA: x), Then to look up the correct function name the compiler considers matching names in the namespace (hereA) Containing the argument's type.

[1] named after Andrew Koenig, who nailed down its definition and is a long-time member of both at&t's c ++ team and the C ++ Standards Committee. See also koenig97.

 

There's a little more to it, but that's essential it. Here's an example, right out of the standard.

namespace NS {  class T { };  void f(T);}NS::T parm;int main(){  f(parm);    // OK, calls NS::f}

I won't delve here into the reasons why Koenig lookup is a good thing (if you want to stretch your imagination right now, take the above Code and replace"NS""STD","T""String", And"F""Operator <"And consider the ramifications). See the next item for much more on Koenig lookup and Its Implications for namespace isolation and for analyzing class dependencies.

Suffice it to say that Koenig lookup is, indeed, a good thing and that you should be aware of how it works, because it can sometimes affect the code you write.

Now back to a simple example:

  void h( A::Y y )   {    h( y );   // which h()?  }}

There is no otherH (A: Y), So thisH ()Callitself with infinite recursion.

AlthoughB: H ()'S signature mentions a type found in namespaceA, This doesn't affect Name Lookup because there are no functions inAMatching the name and signatureH (A: Y).

So, what does it mean? That brings us to the last part of our item Question: analyze the implications.

In short, the meaning of code in namespaceBIs being affected by a function declared in the completely separate namespaceA, Even thoughBHas done nothing but simply mention a type found inAAnd there's nary"Using"In sight.

What this means is that namespaces aren't quite as independent as people originally thought. don't start denouncing namespaces just yet, though; namespaces are still pretty independent, and they fit their intended uses to a T. the purpose of this item is just to point out one of the (rare) Cases in which namespaces aren't quite hermetically sealed inclund, in fact, in which they shoshould not be hermetically sealed, as the following item will show.

Recall a traditional definition of a class:

 

A class describes a set of data, along with the functions that operate on that data.

 

Our question is: what functions are "part of" a class, or make up the interface of a class?

 
I l @ ve ruboard

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.