#include <iostream>
#include <vector>
#include <string>
#include <cstring>
#include <functional>
using namespace std;
template <typename Object, typename Comparator>
const Object &findMax(const vector<Object> &arr,
const Comparator &isLessThan = less<Object>())
{
int maxIndex = 0;
for (int i = 1; i < arr.size(); i++) {
if (isLessThan(arr[maxIndex], arr[i])) {
maxIndex = i;
}
}
return arr[maxIndex];
}
int main()
{
vector<string> arr(3);
arr[0] = "ZED";
arr[1] = "alli";
arr[2] = "crocode";
//...
cout << findMax(arr) << endl;
return 0;
}
当我使用g ++进行编译时,会出现以下错误:
test4.cpp: In function ‘int main()’:
test4.cpp:48:24: error: no matching function for call to ‘findMax(std::vector<std::basic_string<char> >&)’
test4.cpp:48:24: note: candidate is:
test4.cpp:10:15: note: template<class Object, class Comparator> const Object& findMax(const std::vector<Object>&, const Comparator&)
无法从默认参数推导出模板参数。C ++ 11,[temp.deduct.type]§5:
非推论上下文是:
- ...
- 函数参数的参数类型中使用的模板参数,该参数具有默认参数,该默认参数正在为其进行参数推导的调用中使用。
- ...
您可以使用重载来解决此问题:
template <typename Object, typename Comparator>
const Object &findMax(const vector<Object> &arr, const Comparator &isLessThan)
{
int maxIndex = 0;
for (int i = 1; i < arr.size(); i++) {
if (isLessThan(arr[maxIndex], arr[i])) {
maxIndex = i;
}
}
return arr[maxIndex];
}
template <typename Object>
const Object &findMax(const vector<Object> &arr)
{
return findMax(arr, std::less<Object>());
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句