1

I want to sort a vector of arbitrary types, so I wrote the following code:

#include <iostream> #include <vector> #include <algorithm> using namespace std; template<class T> bool compare(T a, T b) { return a < b; } int main() { vector<int> v; v.push_back(3); v.push_back(4); v.push_back(2); v.push_back(1); sort(v.begin(), v.end(), compare); for (size_t i = 0; i < v.size(); i++) { cout << v.at(i) << " "; } return 0; } 

This code is not compiling, with a error message like:

..\src\Test.cpp:22:34: error: no matching function for call to 'sort(std::vector<int>::iterator, std::vector<int>::iterator, <unresolved overloaded function type>)' ..\src\Test.cpp:22:34: note: candidates are: ... and more 

When I implement the compare-function with concrete types, it works. Can someone tell me how to do that with a template-compare-function?

0

2 Answers 2

8

You need to specify which specialization you want:

sort(v.begin(), v.end(), compare<int>); 

Live on Coliru

Sign up to request clarification or add additional context in comments.

Comments

7

compare is not a function, it's a function template that can be used generate functions, such as compare<int> and compare<long>

So to pass a function to sort you need to name a specialization of the function template:

sort(v.begin(), v.end(), compare<int>); 

Alternatively, create a function object and pass that:

struct Compare { template<typename T> bool operator()(T a, Tb) const { return a < b; } }; sort(v.begin(), v.end(), Compare()); 

This function object has a member function template that can compare any types (like your compare) but you don't need to refer to a specific specialization when passing it to sort, you pass a temporary of type Compare and inside the sort algorithm the compiler will select the right specialization of the function template.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.