Anonymous Namespace Ambiguity

前端 未结 5 2077
我在风中等你
我在风中等你 2020-12-18 19:51

Consider the following snippet:

void Foo() // 1
{
}

namespace
{
  void Foo() // 2
  {
  }
}

int main()
{
  Foo(); // Ambiguous.
  ::Foo(); // Calls the Foo         


        
5条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-18 20:01

    The only solution I can think of that doesn't modify the existing namespace arrangement is to delegate main to a function in the anonymous namespace. (main itself is required to be a global function (§3.6.1/1), so it cannot be in an anonymous namespace.)

    void Foo() // 1
    {
    }
    
    namespace
    {
      void Foo() // 2
      {
      }
    }
    
    namespace { // re-open same anonymous namespace
    
        int do_main()
        {
          Foo(); // Calls local, anonymous namespace (Foo #2).
          ::Foo(); // Calls the Foo in the global namespace (Foo #1).
    
          return 0; // return not optional
        }
    
    }
    
    int main() {
        return do_main();
    }
    

提交回复
热议问题