简体   繁体   中英

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

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.

The idiomatic way of doing so (commonly done with swap ):

namespace derp
{
   template <class iterator_t>
   int a_function(iterator_t t1, iterator_t t2)
   {
      using std::distance;
      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;
   }
}

With this construction, custom distance found in the namespace of iterator_t is preferred, but fallbacks to std::distance .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM