Unary_function和函数对象

unary_function and function object

本文关键字:函数 对象 function Unary      更新时间:2023-10-16

函数对象,这是我第一次看到它们,只是找到了一个关于它的例子,以及它是如何工作的

//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;
}

输出:0 1 2 3 4 5 6 7 8 9

老实说,我理解函数对象的语法,但是这个例子并没有给我一个使用这种技术的严重问题,所以我的问题是什么时候我应该使用函数对象?

,我偶然发现了unary_function,我发现了一个关于它的例子(unary_function)和例子看起来相同的匹配:

// 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.

这是否意味着unary_function模板具有特定参数编号的函数对象?我可以定义我自己的函数对象或只是使用unary_function在我的类。

unary_function是一个助手模板,仅用于公开有关可调用类的类型信息。这被一些c++ 11之前版本的函数结构所使用,比如绑定和组合——你只能绑定和组合匹配的类型,这是通过unary_functionbinary_function基类类型来确定的。

在c++ 11中,这已经过时了,因为可变模板提供了一种更通用的方法,并且有了新的std::functionstd::bind,您可以使用这些繁琐的结构和更多的东西来完成c++ 11之前所能做的一切。

实际上,unary_function甚至不是一个函数对象,因为它没有声明操作符()。提供它只是为了简化参数和结果类型的类型。我认为你的程序中不需要它。

当你需要的函数不仅需要传递给函数的数据,而且需要在调用函数之前存储的一些数据时,你应该使用函数对象