【发布时间】:2014-06-27 06:46:52
【问题描述】:
我有一个用户定义类型(学生)的向量。我有 2 个函数,它们几乎相同,只是其中有一个函数调用。
这是两个功能:
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();});
}
这两个函数都可以正常使用,但似乎可以很容易地构建得更好。我想创建一个可以传入 min_element 或 max_element 的函数,例如:
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();});
}
但我无法让它正常工作。我不知道该怎么做。
编辑 - 这就是我调用调度函数 + 错误消息的方式:
std::cout<<"lowest: "<< dispatch(all_students, std::max_element);
错误信息是:
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:
【问题讨论】:
-
您能否详细说明它是如何不起作用的?特别是请展示您如何使用
dispatch功能。 -
如果您同时计算最小值和最大值,请考虑std::minmax_element。