Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ function template using default parameters

Tags:

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

When I compile it with g++, it gives the following error:

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&)
like image 370
tangwenqiang Avatar asked Sep 24 '13 11:09

tangwenqiang


Video Answer


1 Answers

Template parameters cannot be deduced from default arguments. 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.
  • ...

You can get around this using overloading:

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>());
}
like image 73
Angew is no longer proud of SO Avatar answered Sep 27 '22 21:09

Angew is no longer proud of SO