MCP
MCP

Reputation: 4536

optional parameter in template function

I'm trying to add in an optional parameter in a template function... Basically a parameter that overloads the relational operator depending on the user's type. It's my first template funct so I'm pretty basic. This should sort through a vector of the user's type and return the greatest element. Something like:

template <typename Type>
Type FindMax(std::vector<Type> vec, RelationalOverloadHere)
/..../

What would the second "optional" parameter look like?

Upvotes: 2

Views: 5345

Answers (3)

Jesse Good
Jesse Good

Reputation: 52365

Here is a working program showing an example of what I think you are looking for:

#include <vector>
#include <iostream> 
#include <functional>
#include <algorithm>

template <typename Type, typename Compare = std::less<Type>>
Type findmax(std::vector<Type>& v, Compare comp = Compare())
{
    return *std::max_element(v.begin(), v.end(), comp);
}


int main()
{
    int a[] = {1, 11, 232, 2, 324, 21};
    std::vector<int> v(a, a+6);

    std::cout << findmax(v) << std::endl;
}

Upvotes: 1

Philipp
Philipp

Reputation: 49802

Usually this is like

template<typename Type, typename BinaryOperation = std::less<Type> >
Type FindMax(const std::vector<Type>& vec, BinaryOperation op = BinaryOperation());

So the standard comparator is <, but can be customized if desired.

In the standard library, the respective algorithm is max_element with the following overload:

template<typename ForwardIterator, typename Compare>
  ForwardIterator
  max_element(ForwardIterator first, ForwardIterator last, Compare comp);

Upvotes: 6

user405725
user405725

Reputation:

It is not very clear as for what exactly you are asking about.. But..

Here is an optional parameter for which default value is specified in case user does not provide anything:

template <typename Type>
Type FindMax(const std::vector<Type> & vec, int foo = 1 /* <- This is a default that can be overridden. */)
// ...

Upvotes: 1

Related Questions