user943998
user943998

Reputation: 135

unary_function and function object

function object , it' my first time that i seeing them , and just found an example about it and how it's work

//function object example
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
//simple function object that prints the passed argument
class PrintSomething
{
public:
void operator() (int elem) const
{
cout<<elem<<' ';
}
}
;
int main()
{
vector<int> vec;
//insert elements from 1 to 10
for(int i=1; i<=10; ++i)
vec.push_back(i);
//print all elements
for_each (vec.begin(), vec.end(), //range
PrintSomething()); //operation
cout<<endl;
}

output : 0 1 2 3 4 5 6 7 8 9

to be honest with you , i understand the syntax of the function object but this example don't give me a serious issue to use this technique , so my question is when i should use function object ?

and by Accidentally i found unary_function and i found an example about it (unary_function) and the examples look same match :

// unary_function example
#include <iostream>
#include <functional>
using namespace std;

struct IsOdd : public unary_function<int,bool> {
  bool operator() (int number) {return (number%2==1);}
};

int main () {
  IsOdd IsOdd_object;
  IsOdd::argument_type input;
  IsOdd::result_type result;

  cout << "Please enter a number: ";
  cin >> input;

  result = IsOdd_object (input);

  cout << "Number " << input << " is " << (result?"odd":"even") << ".\n";

  return 0;
}

outputs :
 Please enter a number: 2
Number 2 is even.

is this mean that unary_function is template function object with specific arguments number? and i can define my own function object or just use unary_functionin my classes .

and thank you !

Upvotes: 1

Views: 1374

Answers (2)

prazuber
prazuber

Reputation: 1362

Actually, unary_function is not even a function object, since it has no declared operator(). It is provided only to simplify the typedefs of the argument and result types. I don't think you need it in your program.

You should use function object when you need a function which requires not only the data which is passed to the function, but some data which should be stored before the function is called.

Upvotes: 0

Kerrek SB
Kerrek SB

Reputation: 477434

unary_function is a helper template that only serves to expose type information about your callable class. This is used by some pre-C++11 functional constructions like binding and composing - you can only bind and compose matching types, which are determined via the unary_function and binary_function base class typedefs.

In C++11 this has become obsolete, since variadic templates provide a more general, universal approach, and with the new std::function and std::bind you can do everything you could do pre-C++11 with those cumbersome constructions and much, much, much more.

Upvotes: 1

Related Questions