Name

binary_function class template — Base class for binary functionals

Synopsis

template <typename Arg1, typename Arg2, typename Result>
struct binary_function {
  typedef Arg1 first_argument_type;
  typedef Arg2 second_argument_type;
  typedef Result result_type;
};

The binary_function template is a base-class template for all the function classes that represent binary operations. It provides standard names for the argument and result types.

The base template has separate template parameters for each of the argument types and the return type. Many of the predefined function objects in this section use the same type for all three parameters, but you can use different types when defining your own function object, as shown in Example 13-10.

Example

Example 13-10. Functional to round off a floating-point number
// Functional for a binary function that rounds off a floating-point number (of
// type FltT) to a certain number of decimal places (supplied as an unsigned)
template<typename FltT>
struct roundoff : std::binary_function<FltT,unsigned,FltT> {
  FltT operator(  )(FltT x, unsigned digits) const {
    FltT y = std::pow(10.0, static_cast<FltT>(digits));
    FltT z = x * y;
    return (z < 0 ? std::ceil(z - 0.5) : std::floor(z + 0.5)) / y;
  }
};
...
// Copy seq to seq2, rounding off to two decimal places.
std::transform(seq.begin(  ), seq.end(  ), seq2.begin(  ),
  std::bind2nd(roundoff<double>(  ), 2));

Get C++ In a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.