Unary_function和函数对象
unary_function and function object
函数对象,这是我第一次看到它们,只是找到了一个关于它的例子,以及它是如何工作的
//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_function
和binary_function
基类类型来确定的。
在c++ 11中,这已经过时了,因为可变模板提供了一种更通用的方法,并且有了新的std::function
和std::bind
,您可以使用这些繁琐的结构和更多的东西来完成c++ 11之前所能做的一切。
实际上,unary_function甚至不是一个函数对象,因为它没有声明操作符()。提供它只是为了简化参数和结果类型的类型。我认为你的程序中不需要它。
当你需要的函数不仅需要传递给函数的数据,而且需要在调用函数之前存储的一些数据时,你应该使用函数对象
相关文章:
- 如何使用单独文件中的派生类访问友元函数对象
- 当使用透明的std函数对象时,我们还需要写空的尖括号吗
- 有没有办法将重载的类函数绑定到函数对象?
- 将指针传递到成员的指针,从模板参数包到函数对象
- 如何在类模板的成员函数中正确调用函数对象?正在生成 Visual Studio 编译器错误 C2440
- 隐式转换为比较函数对象(函子)用于 std::sort 而不是 std::map?
- C++使用函数对象的线程,如何调用多个析构函数而不是构造函数?
- 如何通过接口将函子分配给函数对象
- 对std::函数对象的调用不匹配,该对象是指向成员函数的指针
- 指向std::invoke中成员函数对象的指针
- 如何成功地将函数对象(或lambda)传递给trackbar回调的第二个参数(void*)
- "std::function"的简单版本:函数对象的生存期?
- C++ 将函数对象作为左值和/或右值传递
- SFINAE 用于具有默认参数的函数对象
- 构造函数对象赋值是否泄漏内存
- 如何发送通过绑定到函数/方法创建的函数对象?
- std::for_each 与函数对象
- 将函数对象传递给 std::function
- 访问执行策略for_each函数对象中的迭代器
- 通过C++函数对象类访问参数