Why class member functions shadow free functions with same name?

There is a special, very surprising, rule (but it does not apply to your example) stating that once a class member name is found by name lookup, no namespace scopes are searched:

#include <string>

struct C {
    std::string s;

    explicit C (std::string);

    void swap (C& rhs) {
        swap (s, rhs.s); // error: swap is C::swap
    }   
};

void swap (C& lhs, C& rhs) {
    swap (lhs.s, rhs.s); // std::swap(string,string)
}

IMO, this is craziness.

But why prohibit unambigious calls where free function has different signature like this:

Name lookup happens before overloading resolution:

  • If lookup is ambiguous, overloading resolution is not done.
  • If no viable function is found by name lookup, no other round of lookup is tried.

The rules are sufficiently complex without "feedback" between overloading and name lookup. I would suggest simplification (like removing the member hides namespace scope name rule, and removing ambiguous name lookup) rather than complexification.


For unqualified name lookup, only one scope at a time is considered, and if the search in that scope doesn't yield any results, the next higher scope is searched. In your case, only S's scope is searched.

But why prohibit unambigious calls where free function has different signature like this:

The problem is that name lookup doesn't concern itself with anything but the name, the identifier. It is completely oblivious to the fact that you want to call a function, it just sees an identifier. The same name lookup happens if you just use auto x = f;, and if you think of it that way, there are very good reasons you only want a very limited scope to search. Anything else would just surprise the user.


I cannot provide an authoritative answer (Maybe some remember a quote from Design and Evolution of C++ or actually has been on the committee at that time), but my first guess would be to exactly fail in cases as you show. It is easy to forget how many things are in scope at a certain time. Additionally overload resolution can be quite complex and there can be default arguments and conversion. So I'd rather have the most limited scope in that case to be always sure what exactly is being called.