模板参数推导编译错误

时间:2020-07-21 04:15:58

标签: c++

我有以下代码,导致在尝试绑定sort()时出现编译错误。我正在尝试重新定义在std::sort()中被调用并通过参数依赖查找绑定的print_sorted()

有人知道为什么print_sorted<string>()实例无法绑定到已声明的命名空间sort()中的std模板吗?为什么编译错误?

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

编译:

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.

0 个答案:

没有答案
相关问题