
Module: Standard C++ Library Library: General utilities
Function
A function adaptor that creates a function object from a pointer to a function
#include <functional>
namespace std {
template<class Arg, class Result>
pointer_to_unary_function<Arg, Result>
ptr_fun(Result (*f)(Arg));
template<class Arg1, class Arg2, class Result>
pointer_to_binary_function<Arg1, Arg2, Result>
ptr_fun(Result (*x)(Arg1, Arg2));
}
The pointer_to_unary_function and pointer_to_binary_function classes encapsulate pointers to functions, and use operator() so that the resulting object serves as a function object for the function.
The ptr_fun() function is overloaded to create instances of pointer_to_unary_function or pointer_to_binary_function when included with the appropriate pointer to a function.
//
// pnt2fnct.cpp
//
#include <algorithm> // for copy, transform
#include <functional> // for ptr_fun
#include <iostream> // cout, endl
#include <iterator> // for ostream_iterator
#include <deque> // for deque
#include <vector> // for vector
int factorial (int x)
{
return x > 1 ? x * factorial (x - 1) : x;
}
int main ()
{
typedef std::deque<int, std::allocator<int> > Deque;
typedef std::vector<int, std::allocator<int> > Vector;
typedef std::ostream_iterator<int, char,
std::char_traits<char> >
Iter;
// Initialize a deque with an array of integers.
const Deque::value_type a[] = { 1, 2, 3, 4, 5, 6, 7 };
Deque d (a + 0, a + sizeof a / sizeof *a);
// Create an empty vector to store the factorials.
Vector v (Vector::size_type (7));
// Compute factorials of the contents of 'd' and
// store results in 'v'.
std::transform (d.begin (), d.end (), v.begin (),
std::ptr_fun (factorial));
// Print the results.
std::cout << "The following numbers: \n ";
std::copy (d.begin (), d.end (), Iter (std::cout," "));
std::cout << "\n\nHave the factorials: \n ";
std::copy (v.begin (), v.end (), Iter (std::cout, " "));
std::cout << std::endl;
return 0;
}
Program Output:
The following numbers:
1 2 3 4 5 6 7
Have the factorials:
1 2 6 24 120 720 5040
Function Objects, pointer_to_binary_function, pointer_to_unary_function, mem_fun
ISO/IEC 14882:1998 -- International Standard for Information Systems -- Programming Language C++, Section 20.3.7
Copyright (c) 1994-2006 Rogue Wave Software, a Quovadx Division.
Licensed under the Apache License, Version 2.0.
Contact Rogue Wave about documentation or support issues. You can also seek help from other developers through the Apache stdcxx community (see below).