#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;
}
Run Code Online (Sandbox Code Playgroud)
当我用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&)
Run Code Online (Sandbox Code Playgroud)
Rei*_*ica 12
无法从默认参数推断出模板参数.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>());
}
Run Code Online (Sandbox Code Playgroud)
默认模板参数和函数参数。使用max_element(实际上,甚至不要定义这个函数,只要max_element在你会调用它的地方使用)。
template <typename Object, typename Comparator = std::less<Object>>
const Object &findMax(const vector<Object> &arr, Comparator comp = Comparator())
{
return *std::max_element(arr.cbegin(), arr.cend(), comp);
}
Run Code Online (Sandbox Code Playgroud)
免责声明:未经测试,必须有 C++11