使用默认参数的 C++ 函数模板

标签 c++ templates

#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:

The non-deduced contexts are:

  • ...
  • A template parameter used in the parameter type of a function parameter that has a default argument that is being used in the call for which argument deduction is being done.
  • ...

您可以使用重载来解决这个问题:

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>());
}

关于使用默认参数的 C++ 函数模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18980781/

相关文章:

c++ - 使用 opencv 匹配一组图像中的图像,以便在 C++ 中进行识别

c++ - 如何访问存储在 Mat C++ 中的 findNonZero 坐标

c++ - 如何不链接 msvcr100.dll?

javascript - 更改模板中元素的类

c++ - 使用模板还是 void?

C++:二维数组;代码无法正常工作。普通学生和分数数组

c++ - 使用 C++ 模板实现访问者模式

c++ - 使用 constexpr 的替代元组迭代

c++ - STL 容器上的模板模板参数

c++ - 链表C++实现