GeneralIdioms

Argument-Dependent Lookup and the Hidden Friend Idiom

Argument-Dependent Lookup (ADL), also known as Koenig Lookup, is a set of “magical” rules for the lookup of unqualified functions based on their function arguments.

GeneralIdioms

 

The Hidden Friend Idiom is based on Argument-Dependent Lookup (ADL). Therefore, let’s start this post with ADL.

Argument-Dependent Lookup

Have you ever wondered why the following program works?

#include <iostream>

int main() {
    std::cout << "Hello world";
}

 

Why should the program not work? The overloaded output operator operator<< is defined in the std namespace. The question is, therefore: How is the appropriate overloaded output operator for std::string found? You may already assume it.

Wikipedia has a nice definition of ADL:

 

Rainer D 6 P2 500x500Modernes C++ Mentoring

Be part of my mentoring programs:

  • "Fundamentals for C++ Professionals" (open)
  • "Design Patterns and Architectural Patterns with C++" (open)
  • "C++20: Get the Details" (open)
  • "Concurrency with Modern C++" (starts March 2024)
  • Do you want to stay informed: Subscribe.

     

    • Argument-Dependent Lookup: In the C++ programming language, argument-dependent lookup (ADL), or argument-dependent name lookup, applies to the lookup of an unqualified function name depending on the types of the arguments given to the function call. This behavior is also known as Koenig lookup, as it is often attributed to Andrew Koenig, though he is not its inventor.(https://en.wikipedia.org/wiki/Argument-dependent_name_lookup)

    Let’s analyze this. Here is a simple example of applying ADL:

    // adl.cpp
    
    namespace MyNamespace {
        struct MyStruct {};
        void function(MyStruct) {}
    }   
    
    int main() {
    
        MyNamespace::MyStruct obj;  
        function(obj);     // (1)
    
    }
    

     

    The call function(obj) in line (1) would fail without Argument-Dependent Lookup. Thanks to ADL, the lookup for unqualified function names includes the namespace of their arguments in addition to the usual unqualified name lookup. Consequentially, the name function is found in the namespace MyNamespace.

    Now, we know what ADL means. But this does not solve our original challenge. Why does the simple “Hello World” program work?

    #include <iostream>
    
    int main() {
        std::cout << "Hello world";
    }
    

     

    Let’s try it out with C++ Insights:https://cppinsights.io/s/bfb25e37

    #include <iostream>
    
    int main()
    {
      std::operator<<(std::cout, "Hello world");  // (1)
      return 0;
    }
    

     

    The call  std::cout << "Hello world"; is equivalent to the function call operator<<(std::cout, "Hello world"); (line 1). ADL regards the namespace of its arguments that includes in our concrete case std::cout.

    Finally, let me write about the Hidden Friend Idiom.

     

    Hidden Friend Idiom

    Argument-Dependend Lookup extends the public interface of a class: non-member functions or non-member operators extend the public interface of that class. Now, the Hidden Friend Idiom kicks in:

    Friend functions or operators defined inside the class have two special properties:

    1. They can access the private members of the class.
    2. They are non-member functions or operators.

    The second point is pretty unknown, and I regularly have to explain it when I give a class.  A friend function defined inside the class has interesting consequences for the overloading of operators. Friend operators defined inside the class can access the private members of the class, are non-member functions, and are found by Argument-Dependent Lookup.

     

    // hiddenFriend.cpp
    
    #include <iostream>
    
    class MyDistance{
     public:
        explicit MyDistance(double i):m(i){}
    
        friend MyDistance operator +(const MyDistance& a, const MyDistance& b){         // (1)
            return MyDistance(a.m + b.m);
        }
        
        friend MyDistance operator -(const MyDistance& a, const MyDistance& b){         // (2)
            return MyDistance(a.m - b.m);
        }
    
        friend std::ostream& operator<< (std::ostream &out, const MyDistance& myDist){  // (3)
            out << myDist.m << " m";
            return out;
        }
        
     private:
        double m;
    
    };
    
    
    int main() {
    
        std::cout << '\n';
    
        std::cout << "MyDistance(5.5) + MyDistance(5.5): " << MyDistance(5.5) + MyDistance(5.5) << '\n';  // (4)
    
        std::cout << "MyDistance(5.5) - MyDistance(5.5): " << MyDistance(5.5) - MyDistance(5.5) << '\n';  // (5)
    
        std::cout << '\n';
    
    }
    

     

    All three operators in lines (1), (2), and (3) are friends. The corresponding operators (+) in line (4) and (-) in line (5) are found as expected.

    C++ Insights shows once more the magic of operator overloading: https://cppinsights.io/s/50aae5ed

    In particular, the addition in line (4) (MyDistance(5.5) + MyDistance(5.5)) is transformed into: operator+(MyDistance(5.5), MyDistance(5.5)).

    Finally, here is the output of the program:

    hiddenFriend

    On the contrary, let me remove the friend declaration from the overloaded+ operator.

     

    class MyDistance{
     public:
        explicit MyDistance(double i):m(i){}
    
        MyDistance operator +(const MyDistance& a, const MyDistance& b){        
            return MyDistance(a.m + b.m);
        }
        
        friend MyDistance operator -(const MyDistance& a, const MyDistance& b){      
            return MyDistance(a.m - b.m);
        }
    
        friend std::ostream& operator<< (std::ostream &out, const MyDistance& myDist){ 
            out << myDist.m << " m";
            return out;
        }
        
     private:
        double m;
    
    };
    

     

    Now, the compilation fails:

    hiddenFriendBroken

     

    The compiler essentially complains in the first line that the definition of the operator+ can only have zero or one argument (hiddenFriend:9:16). Without the friend declaration, the operator+ is a member function, and as such, it has an implicit this pointer. This means that the operator+ has in sum three arguments. That is not valid c++. Consequentially, the compiler does not find the appropriate operator+ (hiddenFriend:32:75).

    What’s Next?

    In addition to the Hidden Friend Idiom, C++ has many more idioms for class design. In my next post, I will write about the Rule of Zero, Five, or Six.

     

     

     

    Thanks a lot to my Patreon Supporters: Matt Braun, Roman Postanciuc, Tobias Zindl, G Prvulovic, Reinhold Dröge, Abernitzke, Frank Grimm, Sakib, Broeserl, António Pina, Sergey Agafyin, Андрей Бурмистров, Jake, GS, Lawton Shoemake, Jozo Leko, John Breland, Venkat Nandam, Jose Francisco, Douglas Tinkham, Kuchlong Kuchlong, Robert Blanch, Truels Wissneth, Kris Kafka, Mario Luoni, Friedrich Huber, lennonli, Pramod Tikare Muralidhara, Peter Ware, Daniel Hufschläger, Alessandro Pezzato, Bob Perry, Satish Vangipuram, Andi Ireland, Richard Ohnemus, Michael Dunsky, Leo Goodstadt, John Wiederhirn, Yacob Cohen-Arazi, Florian Tischler, Robin Furness, Michael Young, Holger Detering, Bernd Mühlhaus, Stephen Kelley, Kyle Dean, Tusar Palauri, Juan Dent, George Liao, Daniel Ceperley, Jon T Hess, Stephen Totten, Wolfgang Fütterer, Matthias Grün, Phillip Diekmann, Ben Atakora, Ann Shatoff, Rob North, Bhavith C Achar, Marco Parri Empoli, moon, Philipp Lenk, Hobsbawm, Charles-Jianye Chen, and Keith Jeffery.

    Thanks, in particular, to Jon Hess, Lakshman, Christian Wittenhorst, Sherhy Pyton, Dendi Suhubdy, Sudhakar Belagurusamy, Richard Sargeant, Rusty Fleming, John Nebel, Mipko, Alicja Kaminska, Slavko Radman, and David Poole.

    My special thanks to Embarcadero
    My special thanks to PVS-Studio
    My special thanks to Tipi.build 
    My special thanks to Take Up Code
    My special thanks to SHAVEDYAKS

    Seminars

    I’m happy to give online seminars or face-to-face seminars worldwide. Please call me if you have any questions.

    Standard Seminars (English/German)

    Here is a compilation of my standard seminars. These seminars are only meant to give you a first orientation.

    • C++ – The Core Language
    • C++ – The Standard Library
    • C++ – Compact
    • C++11 and C++14
    • Concurrency with Modern C++
    • Design Pattern and Architectural Pattern with C++
    • Embedded Programming with Modern C++
    • Generic Programming (Templates) with C++
    • Clean Code with Modern C++
    • C++20

    Online Seminars (German)

    Contact Me

    Modernes C++ Mentoring,

     

     

    0 replies

    Leave a Reply

    Want to join the discussion?
    Feel free to contribute!

    Leave a Reply

    Your email address will not be published. Required fields are marked *