Search code examples
c++namespacesoverloadingname-lookup

Function overloading between anonymous namespace and named namespace


Is this not allowed? Can someone please explain why?

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

The error I run into is:

> /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);

Solution

  • Your code leads to recursion call. When kthLargest is called inside Algorithms::kthLargest, the name kthLargest will be found at the namespace Algorithms, then name lookup stops, no further scopes (e.g. global namespace) will be examined. After that, overload resolution is performed and fails because arguments don't match.

    You can change it to

    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);
          //     ^^
       }
    }
    

    or

    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);
       }
    }