Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Does member function like operator<< , operator* need ADL to work?

I have a code snippet (Hypothetically):

#include <iostream>

struct Pirate {
 void song_name() {
  std::cout << "Bink's Sake\n";
 }

 Pirate& operator*(Pirate const& other) {
  // do something
  return *this;
 }
};

int main() {
 Pirate p1{} p2{};
 p1.song_name(); // does this use qualified or unqualifed name lookup?
 
 p1 * p2;

 std::cout << 5;
 std::cout << 'a';
}

Does p1 * p2 use qualified name lookup or unqualified name lookup or ADL?

std::cout << 5 transforms into std::cout.operator<<(5);
std::cout << 'a' transforms into std::operator<<(std::cout, 'a');

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Does member functions require ADL to work?
Does the above two statments use qualified or unqualifed name lookup or ADL?

Thanks

>Solution :

A name is a qualified name if the scope to which it belongs is explicitly denoted using a scope-resolution operator (::) or a member access operator (. or ->).

Case 1

Thus, when you wrote:

p1.song_name(); //here p1.song_name is a qualified name

In the above statement, p1.song_name is a qualified name and so here qualified lookup takes place.

Case 2

Next, when your wrote:

p1 * p2;

The above statement is equivalent to:

p1.operator*(p2);

Since your class Pirate have an overloaded member function operator*, the above statement will use that member function. The above statement uses qualified lookup as well because we have used the member access operator ..

Case 3

Here we have the statement:

std::cout << 5;

The above statement is equivalent to:

std::cout.operator<<(5);

which uses qualified lookup since it has member access operator .

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading