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.

1
  • The key is <return type> operator()(some args...); Commented Sep 2, 2014 at 4:27

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.