Calling a function overloaded in several namespaces from inside one namespace

前端 未结 3 536
广开言路
广开言路 2021-01-02 16:51

I have the following code snippet:

void foo(double a) {}

namespace bar_space
{
  struct Bar {};

  void foo(Bar a) {}
}

foo(double) is a g

相关标签:
3条回答
  • 2021-01-02 17:29

    In C++, there is a concept called name hiding. Basically, a function or class name is "hidden" if there is a function/class of the same name in a nested scope. This prevents the compiler from "seeing" the hidden name.

    Section 3.3.7 of the C++ standard reads:

    A name can be hidden by an explicit declaration of that same name in a nested declarative region or derived class (10.2)

    So, to answer your question: in your example void foo(double a); is hidden by void bar_space::foo(Bar a); So you need to use the :: scoping operator to invoke the outer function.

    0 讨论(0)
  • 2021-01-02 17:49

    However, in your sample code you could use something like that

    namespace bar_space 
    {
        using ::foo;
        void baz()
        {
           Bar bar;
           foo(5.0);
           foo(bar);
        }
    }
    
    0 讨论(0)
  • 2021-01-02 17:49

    Yes, bar_space is hiding the original function and no, you can't make foo(5.0) callable from whithin bar_space without explicit scoping if foo(double) is defined in the global namespace.

    0 讨论(0)
提交回复
热议问题