1

What is the reason why the function bar() can't be overloaded here?

namespace foo
{
    void bar(int) { }

    struct baz
    {
        static void bar()
        {
            // error C2660: 'foo::baz::bar' : function does not take 1 arguments
            bar(5); 
        }
    };
}
user541686
  • 205,094
  • 128
  • 528
  • 886

2 Answers2

5

It cannot be overloaded because they are at different scopes. The first bar is at foo::bar while the second one is at foo::baz::bar.

The name bar from the outer namespace is hidden by the new declaration. It has to either be called explicitly, or made visible by a using declaration:

static void bar()
{
    using foo::bar;
    bar(5); 
}
K-ballo
  • 80,396
  • 20
  • 159
  • 169
  • Right, but couldn't a failure tell the compiler that it should continue searching? Why does it fail without trying something else? – user541686 Oct 25 '11 at 00:01
  • 2
    Compiler doesn't work by hit and trial. It works the way you ask it to work. It can optimize but cannot take intelligent decisions on behalf of you. Moreover, as the scope of your functions is different there is no way for the compiler to determine what implementation you want to use. Consider that you have more than two bar functions defined in more than two scopes. Then it would be better for the compiler to throw an error rather than being intelligent and picking an implementation which may or may not suit you. – krammer Oct 25 '11 at 00:05
  • Ah, I just realized that, if the compiler did this, it would allow for hijacking of a member function, because of implicit conversions that might turn out to be worse matches locally than globally. I think it might be a good idea to mention this too. – user541686 Oct 25 '11 at 01:23
  • @krammer: `Compiler doesn't work by hit and trial.` --> SFINAE? – user541686 Oct 25 '11 at 01:42
0

Is this what you're trying to do?

namespace foo
{
    void bar(int) { }

    struct baz
    {
        static void bar()
        {
            // error C2660: 'foo::baz::bar' : function does not take 1 arguments
            foo::bar(5); // <-- changed
        }
    };
}

EDIT: That's also obviously not going to be overloading.

AusCBloke
  • 18,014
  • 6
  • 40
  • 44