user2023370
user2023370

Reputation: 11037

C++ global namespace access from within another namespace

In the C++ code below, foobar is defined first for a single double parameter, and then again for a single parameter of type Foo. Both are defined within the global namespace.

Within the one namespace, a further overload of foobar is defined, with a single parameter of type Bar. From this version of foobar, an unqualified call to foobar with a double argument (42.0) will fail. A similar call to foobar, this time qualified with the (::) scope resolution operator, also with a double argument, will though succeed.

On the other hand, an unqualified call to foobar, with an argument of type Foo, succeeds. A call to foobar with a Foo argument, qualified by the scope resolution operator, also succeeds.

Why do the two scenarios behave differently? I use both gcc 4.7 and clang++ 3.2.

struct Foo {};
struct Bar {};

double foobar(double x) { return x; }
Foo    foobar(Foo f)    { return f; }

namespace one {

  Bar foobar(Bar b) {
    //foobar(42.0); // error: can't convert to Bar
    ::foobar(42.0);

    Foo f;
      foobar(f);    // no problem
    ::foobar(f);
    return b;
  }
};

Upvotes: 9

Views: 1114

Answers (1)

Bo Persson
Bo Persson

Reputation: 92211

Argument dependent lookup.

In the call foobar(f) functions from the namespace of Foo will be considered.

Doesn't work for double because that type is not declared in any namespace.

Upvotes: 8

Related Questions