2015-06-19 11 views
7
#include <algorithm> 
#include <vector> 

template <class BidirectionalIterator, class UnaryPredicate> 
BidirectionalIterator partition(BidirectionalIterator first, 
    BidirectionalIterator last, UnaryPredicate pred) 
{ 
    while (first != last) { 
     while (pred(*first)) { 
      ++first; 
      if (first == last) return first; 
     } 
     do { 
      --last; 
      if (first == last) return first; 
     } while (!pred(*last)); 
     std::swap(*first, *last); 
     ++first; 
    } 
    return first; 
} 

int main() { 
    std::vector<int> v = { 1, 55, 17, 65, 40, 18, 77, 37, 77, 37 }; 
    partition(v.begin(), v.end(), [](const int &i) { 
     return i < 40; 
    }); 
    return 0; 
} 

Il codice non verrà compilato. Sia clang ++ (3.5.2/cygwin) che Visual Studio (2013) si lamentano della chiamata ambigua. Poiché non viene utilizzata la direttiva using, non capisco cosa c'è che non va. Per compilare correttamente, utilizzare il prefisso ::.clang ++: errore: la chiamata a 'partition' è ambigua

risposta

8

tuo partition ha una collisione nome con std::partition

Il motivo lo sta facendo, anche senza il prefisso std:: è perché sta usando argument dependent lookup (ADL) sugli argomenti, che sono std::vector<int>::iterator, che portano lo spazio dei nomi std::. Pertanto, il compilatore è in grado di "vedere" la funzione std::partition e la funzione partition.

From cppreference (sottolineatura mia)

... for every argument in a function call expression and for every template argument of a template function, its type is examined to determine the associated set of namespaces and classes that it will add to the lookup

Problemi correlati