匿名命名空间和命名空间之间的函数重载

4

这种做法不允许吗?可以有人解释一下为什么吗?

Algorithms.h

namespace Algorithms
{
  int kthLargest(std::vector<int> const& nums, int k);    
}

Algorithms.cpp

#include "Algorithms.h"
namespace
{
int kthLargest(std::vector<int> const& nums, int start, int end, int k)
{
   <implementation>
}
} // end anonymous namespace

namespace Algorithms
{
   int kthLargest(std::vector<int> const& nums, int k)
   {
      return kthLargest(nums, 0, nums.size() - 1, k);
   }
} // end Algorithms namespace

我遇到的错误是:

> /usr/bin/c++   -I../lib/algorithms/inc  -MD -MT
> lib/algorithms/CMakeFiles/algorithms.dir/src/Algorithms.o -MF
> lib/algorithms/CMakeFiles/algorithms.dir/src/Algorithms.o.d -o
> lib/algorithms/CMakeFiles/algorithms.dir/src/Algorithms.o -c
> ../lib/algorithms/src/Algorithms.cpp
> ../lib/algorithms/src/Algorithms.cpp: In function ‘int
> Algorithms::kthLargest(const std::vector<int>&, int)’:
> ../lib/algorithms/src/Algorithms.cpp:70:50: error: too many arguments
> to function ‘int Algorithms::kthLargest(const std::vector<int>&, int)’
> return kthLargest(nums, 0, nums.size() - 1, k);

请注意,标准库中有 std::nth_element 函数。 - Jarod42
1个回答

6
你的代码导致递归调用。当在Algorithms::kthLargest内部调用kthLargest时,名称kthLargest将在命名空间Algorithms中找到,然后名称查找停止,不会再检查其他作用域(如全局命名空间)。之后,进行重载决议并失败,因为参数不匹配。
你可以将其更改为:
namespace Algorithms
{
   int kthLargest(std::vector<int> const& nums, int k)
   {
      // refer to the name in global namespace
      return ::kthLargest(nums, 0, nums.size() - 1, k);
      //     ^^
   }
}

或者

namespace Algorithms
{
   using ::kthLargest;  // introduce names in global namespace
   int kthLargest(std::vector<int> const& nums, int k)
   {
      return kthLargest(nums, 0, nums.size() - 1, k);
   }
} 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接