[英]C++ function template using default parameters
#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>());
}
默认为模板参数和函数参数。 使用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);
}
免责声明:未经测试,必须具有C ++ 11
在C ++ 11中使用默认模板参数,可以这样编写函数:
template <typename Object, typename Comparator = std::less<Object> >
const Object &findMax(const vector<Object> &arr, const Comparator isLessThan = Comparator())
{
int maxIndex = 0;
for (int i = 1; i < arr.size(); i++) {
if (isLessThan(arr[maxIndex], arr[i])) {
maxIndex = i;
}
}
return arr[maxIndex];
}
注意默认模板参数typename Comparator = std::less<Object>
的用法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.