Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

optional parameter in template function

Tags:

c++

templates

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?

like image 480
MCP Avatar asked Aug 14 '26 05:08

MCP


1 Answers

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);
like image 59
Philipp Avatar answered Aug 16 '26 20:08

Philipp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!