Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
  }
};
like image 990
user2023370 Avatar asked Aug 08 '12 21:08

user2023370


1 Answers

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.

like image 54
Bo Persson Avatar answered Oct 25 '22 10:10

Bo Persson