Enabling ADL for distance within a non-std:: namespace, with a fallback to std::distance

  argument-dependent-lookup, c++

My use-case is as follows – within a non-std:: namespace, a class has a templated member function which takes in 2 (templated) iterators as parameters, and part of the function call involves calling distance() on those iterators.
The problem is, some containers have their own overload for distance() for their iterators. So if I specify std::distance, this is not sufficient.
However because the class is not within the std:: namespace, the call to distance without the std:: qualifier will not resolve to std::distance on containers without their own distance() overload.

How can I rework the problem (if possible) such that std::distance ends up getting called where necessary, but not when an overload exists for the iterator in question?

Example code (not actual code):

namespace derp
{
   template <class iterator_t>
   int a_function(iterator_t t1, iterator_t t2)
   {
      int a = distance(t1, t2); // want to resolve to std::distance if, for example, iterator is from std::vector
      // Do stuff with a and t1/t2
      return a;
   }
}

Templating to std::vector etc is not possible, as there are too many std:: containers and it would cause code bloat.

Source: Windows Questions C++

LEAVE A COMMENT