c++模板给出了无法解析的函数类型

C++ Template gives unresolved function type

本文关键字:函数 类型 c++      更新时间:2023-10-16

我正在尝试制作一个模板,比较第二项对:

template <class T>
bool sortPairKey2(T u,  T v) { return u.second < v.second;}

这样,如果我有一对对,我仍然可以使用这个函数

但是当我在sort方法(from)中使用它时,我得到:

error: no matching function for call to ‘sort(std::vector<std::pair<int, int> >::iterator, std::vector<std::pair<int, int> >::iterator, <unresolved overloaded function type>)’
     sort(sums.begin(), sums.end(), sortPairKey2<iipair,iipair>);
                                                               ^
stp2mzn.cpp:409:63: note: candidates are:
In file included from /usr/include/c++/4.8/algorithm:62:0,
                 from stp2mzn.cpp:9:
/usr/include/c++/4.8/bits/stl_algo.h:5447:5: note: template<class _RAIter> void std::sort(_RAIter, _RAIter)
     sort(_RandomAccessIterator __first, _RandomAccessIterator __last)
     ^
/usr/include/c++/4.8/bits/stl_algo.h:5447:5: note:   template argument deduction/substitution failed:
stp2mzn.cpp:409:63: note:   candidate expects 2 arguments, 3 provided
     sort(sums.begin(), sums.end(), sortPairKey2<iipair,iipair>);
                                                               ^
In file included from /usr/include/c++/4.8/algorithm:62:0,
                 from stp2mzn.cpp:9:
/usr/include/c++/4.8/bits/stl_algo.h:5483:5: note: template<class _RAIter, class _Compare> void std::sort(_RAIter, _RAIter, _Compare)
     sort(_RandomAccessIterator __first, _RandomAccessIterator __last,
     ^
/usr/include/c++/4.8/bits/stl_algo.h:5483:5: note:   template argument deduction/substitution failed:
stp2mzn.cpp:409:63: note:   couldn't deduce template parameter ‘_Compare’
     sort(sums.begin(), sums.end(), sortPairKey2<iipair,iipair>);

其中typedef pair<int,int> iipair .

函数工作良好时,而不是T我有pair<int,int>。我看不出有什么问题。

谢谢!

请尝试sortPairKey2<iipair>代替sortPairKey2<iipair,iipair>

两件事。

  1. 你应该通过const引用
  2. 传递参数
  3. 不写sortPairKey2<iipair, iipair>,要么完全摆脱模板规范(你的编译器应该找到它),要么直接写sortPairKey2<iipair>