1

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.

Community
  • 1
  • 1

1 Answers1

2

BinaryOp op = BinaryOp() is copy-initializing an instance of BinaryOp from a default-constructed temporary. The default template argument is std::greater which is the default type aliased by BinaryOp. Using () on any class type causes a constructor call. In this code you are creating a default parameter of type std::greater.

Next, where you are calling op(), you are actually invoking a member operator bool operator()(const value_type&, condt value_type&). This allows op to act like a function object.

David G
  • 94,763
  • 41
  • 167
  • 253