C++ 一元函数与函数对象
函数对象,这是我第一次看到它们,我刚刚找到了一个关于它的例子,以及它是如何工作的C++ 一元函数与函数对象,c++,C++,函数对象,这是我第一次看到它们,我刚刚找到了一个关于它的例子,以及它是如何工作的 //function object example #include <iostream> #include <vector> #include <algorithm> using namespace std; //simple function object that prints the passed argument class PrintSomething { publi
//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;
}
这是否意味着一元函数
是模板具有特定参数编号的函数对象?
我可以定义自己的函数对象,也可以在我的类中使用一元函数
谢谢你 实际上,一元函数甚至不是函数对象,因为它没有声明的运算符()。提供它只是为了简化参数和结果类型的typedef。我认为你的计划不需要它
当您需要的函数不仅需要传递给函数的数据,还需要在调用函数之前存储的一些数据时,应该使用函数对象。实际上,一元函数甚至不是函数对象,因为它没有声明的运算符()。提供它只是为了简化参数和结果类型的typedef。我认为你的计划不需要它
当您需要的函数不仅需要传递给函数的数据,还需要在调用函数之前存储的一些数据时,您应该使用函数对象。
一元函数
是一个帮助器模板,它仅用于公开有关可调用类的类型信息。这被一些C++11之前的函数构造(如绑定和组合)使用-您只能绑定和组合匹配类型,这些类型是通过一元函数
和二元函数
基类typedef确定的
在C++11中,这已经过时了,因为可变模板提供了一种更通用的方法,并且通过新的
std::function
和std::bind
可以用这些繁琐的构造和很多很多,更多信息。一元函数
是一个助手模板,只用于公开有关可调用类的类型信息。这被一些C++11之前的函数构造(如绑定和组合)使用-您只能绑定和组合匹配类型,这些类型是通过一元函数
和二元函数
基类typedef确定的
在C++11中,这已经过时了,因为可变模板提供了一种更通用的方法,并且有了新的
std::function
和std::bind
,在C++11之前,你可以用这些繁琐的构造和更多、更多、更多的东西来做任何事情。如果你喜欢函数对象,你可能会喜欢更多。如果你喜欢函数对象,你可能会喜欢更多。
// 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.