I have the following code that results in a compilation error trying to bind sort()
. I'm trying to redefine std::sort()
that is being called in print_sorted()
and bound via argument-dependent-lookup.
Does anyone know why the print_sorted<string>()
instantiation is unable to bind to the sort()
template in declared namespace std
? Why the compilation error?
Thans
#include <iostream>
#include <vector>
template<typename T>
void print_sorted(std::vector<T>& v)
{
sort(v.begin(),v.end());
for (const auto& x : v)
std::cout << x << '\n';
}
//#include <algorithm>
namespace std {
template<class T>
void sort(typename std::vector<T>::iterator b,
typename std::vector<T>::iterator e)
{}
#if 0
void sort(typename std::vector<string>::iterator b,
typename std::vector<string>::iterator e)
{
}
#endif
}
int main(int argc, char *argv[])
{
std::vector<std::string> v = {"b", "a"};
print_sorted(v); // sort using std::sort, then print using std::cout
return 0;
}
// point of instantiation
Compilation:
clang++ -pedantic -Wall -std=c++11 test187.cc && ./a.out
test187.cc:7:5: error: no matching function for call to 'sort'
sort(v.begin(),v.end());
^~~~
test187.cc:31:5: note: in instantiation of function template specialization
'print_sorted<std::__cxx11::basic_string<char> >' requested here
print_sorted(v); // sort using std::sort, then print using std::cout
^
test187.cc:15:10: note: candidate template ignored: couldn't infer template
argument 'T'
void sort(typename std::vector<T>::iterator b,
^
1 error generated.