excalibur1491
excalibur1491

Reputation: 1221

C++ Template gives unresolved function type

I am trying to make a template that compares the second item of pairs:

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

this way if I have pairs of pairs, I can still use the function.

But when I use it in the sort method (from ) I get:

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>);

where typedef pair<int,int> iipair.

the function worked fine when instead of T I had pair<int,int>. I dont see what its problem is.

Thank you!

Upvotes: 0

Views: 229

Answers (2)

hellow
hellow

Reputation: 13420

Two things.

  1. you should to pass the parameter by const reference
  2. don't write sortPairKey2<iipair, iipair>, either get rid of the template specification completely (your compiler should figure it out), or just write sortPairKey2<iipair>

Upvotes: 3

nkdm
nkdm

Reputation: 1240

Please try sortPairKey2<iipair> instead of sortPairKey2<iipair,iipair>

Upvotes: 4

Related Questions