function template
<functional>

std::ptr_fun

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 (*f)(Arg1,Arg2));
Convert function pointer to function object
Returns a function object that encapsulates function f.

Function objects are objects whose class defines member function operator(). This member function allows the object to be used with the same syntax as a regular function call. Several standard algorithms and adaptors are designed to be used with function objects.

It is defined with the same behavior as:

1
2
3
4
5
6
7
8
9
10
11
template <class Arg, class Result>
  pointer_to_unary_function<Arg,Result> ptr_fun (Result (*f)(Arg))
{
  return pointer_to_unary_function<Arg,Result>(f);
}

template <class Arg1, class Arg2, class Result>
  pointer_to_binary_function<Arg1,Arg2,Result> ptr_fun (Result (*f)(Arg1,Arg2))
{
  return pointer_to_binary_function<Arg1,Arg2,Result>(f);
}


Template parameters

Arg, Arg1, Arg2
Types of the function's arguments.
Result
Function's return type.

Parameters

f
Pointer to a function, taking either one argument (of type Arg) or two arguments (of types Arg1 and Arg2) and returning a value of type Result.

Return value

A function object equivalent to f.
pointer_to_unary_function and pointer_to_binary_function are function object types, derived respectively from unary_function and binary_function.

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// ptr_fun example
#include <iostream>
#include <functional>
#include <algorithm>
#include <cstdlib>
#include <numeric>
using namespace std;

int main () {
  char* foo[] = {"10","20","30","40","50"};
  int bar[5];
  int sum;
  transform (foo, foo+5, bar, ptr_fun(atoi) );
  sum = accumulate (bar, bar+5, 0);
  cout << "sum = " << sum << endl;
  return 0;
}


Possible output:

sum = 150

See also