1. 函数符定义
函数对象,也叫做函数符,定义:
函数符是可以和()结合起来完成函数调用的符号,有三种
函数名,函数指针,重载了operator()()函数的对象
#include <iostream>
#include <list>
#include <algorithm>
using namespace std;
/*function name*/
/*function ptr*/
/*operator()(...)*/
void out_int(int const& that)
{
cout << that << ' ';
}
bool tooBig(int const that)
{
return that > 50;
}
template <typename T>
class tooBig2
{
private:
T m_cut;
public:
tooBig2(T const& val):m_cut(val){}
bool operator()(T const& that)
{
return that > m_cut;
}
};
void ((*out_int_ptr)(int const&)) = out_int;
int main()
{
int vals[10] = {10,20,30,40,50,60,70,80,90,100};
list<int> list1(vals,vals + 10);
/*out_int(*iterator)*/
for_each(list1.begin(),list1.end(),out_int);
cout << endl; /*10~100*/
/*out_int_ptr(*iterator)*/
for_each(list1.begin(),list1.end(),out_int_ptr);
cout << endl; /*10~100*/
/*tooBig(*iterator)*/
list1.remove_if(tooBig);
for_each(list1.begin(),list1.end(),out_int_ptr);
cout << endl; /*10~50*/
tooBig2<int> big40(40);
/*big40(*iterator)*/
list1.remove_if(big40);
for_each(list1.begin(),list1.end(),out_int_ptr);
cout << endl; /*10~40*/
return 0;
}
2. 预定义的函数符
| 运算符 | 函数符 |
|---|---|
| + | plus |
| - | minus |
| * | multiplies |
| / | divides |
| % | modulus |
| - | negate |
| == | equal_to |
| != | not_equal_to |
| > | greater |
| < | less |
| >= | greater_equal |
| <= | less_equal |
| && | logical_and |
| || | logical_or |
| ! | logical_not |
示例用法
#include <fuctional>
plus<double> add;
double y = add(2.2,2.3);
3. 自适应函数符
2. 一节中例举的函数符都是自适应函数符:自适应函数定义了参数类型与返回类型
//一元函数结构
template <class Arg, class Result>
struct unary_function
{
typedef Arg argument_type; //参数类型,可以理解为x对应的类型
typedef Result result_type;//返回值类型,可以理解为 z 对应的类型
};
//二元函数结构
template <class Arg1, class Arg2, class Result>
struct binary_function
{
typedef Arg1 first_argument_type; //第一个参数类型,可以理解为x对应的类型
typedef Arg2 second_argument_type;//第二个参数类型,可以理解为y对应的类型
typedef Result result_type; //返回值类型,可以理解为 z 对应的类型
};
自适应函数符
//取负,接受一个参数
template <class T>
struct negate : public unary_function<T, T> {
T operator()(const T& x) const { return -x; }
};
//小于,接受两个参数
template <class T>
struct less : public binary_function<T, T, bool> {
bool operator()(const T& x, const T& y) const { return x < y; }
};
4. 自适应适配器
自适应函数符可以结合适配器生成新的函数符
读者可以参看有关bind1st模板类的stl实现
https://www.cnblogs.com/chuyongliu/p/5308616.html

1014

被折叠的 条评论
为什么被折叠?



