I am working through the exercises in accelerated c++, and I am currently working on the chapter regarding generic functions. I came across an algorithm that I wanted to write that required, I think, the value_type of a given iterator. I came across this post Default template arguments for function templates , which helped a lot, but I am wondering if my approach is correct. I don't want to get into a bad habit if that is indeed the case.
template <class ForwardIt, class BinaryOp = std::greater<std::iterator_traits<ForwardIt>::value_type> >
ForwardIt maxInRange(ForwardIt begin, ForwardIt end, BinaryOp op = BinaryOp()) {
// test here to reduce the loop count by 1
if (begin == end)
return begin;
ForwardIt largest = begin;
while (++begin != end)
if (op(*begin, *largest))
largest = begin;
return largest;
}
One more question, sorry. How does the syntax regarding the BinaryOp type parameter work? I don't quite understand how calling a type as if it were a function produces a substitute-like effect. Thanks for your time. I really appreciate it.