I have a vector of a user defined type (Student). I have 2 functions which are almost identical except for a single function call inside them.
Here is the 2 functions:
Student lowest_grade(const std::vector<Student> &all_students){
return *std::min_element(std::begin(all_students), std::end(all_students),
[](const Student &a, const Student &b){
return a.get_average() < b.get_average();});
}
Student highest_grade(const std::vector<Student> &all_students){
return *std::max_element(std::begin(all_students), std::end(all_students),
[](const Student &a, const Student &b){
return a.get_average() < b.get_average();});
}
Both of these functions are working correctly for my use but it seems like this could easily be constructed better. I want to create a function which I could pass in either min_element or max_element, something like:
template <typename func>
Student dispatch(const std::vector<Student> &all_students, func){
return *func(std::begin(all_students), std::end(all_students),
[](const Student &a, const Student &b){
return a.get_average() < b.get_average();});
}
But I can't manage to get this to work properly. I am not sure how to go about doing this.
EDIT - This is how I am calling the dispatch function + the error message:
std::cout<<"lowest: "<< dispatch(all_students, std::max_element);
The error message is:
g++ m.cpp -std=c++11 -Wall -o main
m.cpp: In function ‘int main()’:
m.cpp:86:63: error: missing template arguments before ‘(’ token
std::cout<<"lowest: "<< dispatch(all_students, std::function(std::max_element));
^
ryan@ryan-VirtualBox:~/Desktop/Prog/daily/167m$ make
g++ m.cpp -std=c++11 -Wall -o main
m.cpp: In function ‘int main()’:
m.cpp:86:81: error: no matching function for call to ‘dispatch(std::vector<Student>&, <unresolved overloaded function type>)’
std::cout<<"lowest: "<< dispatch<std::function>(all_students, std::max_element);
^
m.cpp:86:81: note: candidate is:
m.cpp:71:9: note: template<class func> Student dispatch(const std::vector<Student>&, func)
Student dispatch(const std::vector<Student> &all_students, func){
^
m.cpp:71:9: note: template argument deduction/substitution failed:
dispatchfunction.