Function object is very userful to use member function or non-member function as callback mechanism,
Same as event or delegate in C#.

For pointer to object

 template <class Return, class Type, class Argument>
class MemFunctionObject : public binary_function <Type*,Argument,Return>
{
Return (Type::*pMemFunction)(Argument);
public:
explicit MemFunctionObject( Return (Type::*pMF)(Argument) ) : pMemFunction (pMF)
{
}
Return operator() (Type* pObject, A x) const
{
return (pObject->*pMemFunction)(x);
}
};

For reference to object

 template <class Result, class Type, class Argument>
class MemFunctionObjectRef: public binary_function <Type,Argument,S>
{
private:
Result (Type::*pMemMethod)(Argument);
public:
explicit MemFunctionObjectRef ( Result (Type::*p)(Argument) ) : pMemMethod (p) {}
Result operator() (Type& refObject, Argument x) const
{
return (refObject.*pMemMethod)(x);
}
};

 binary_function  define type's alias

 template <class Arg1, class Arg2, class Result>
struct binary_function {
typedef Arg1 first_argument_type;
typedef Arg2 second_argument_type;
typedef Result result_type;
};

Now, wo can define a function to generate a function object

 template <class Result, class Type, class Argument>
MemFunctionObject<Result,Type,Argument> MemFunction(Result (Type::*f)(Argument))
{
return MemFunctionObject<Result,Type,Argument>(f);
}

How to use:

 // mem_fun example
#include <iostream>
#include <functional>
#include <vector>
#include <algorithm>
#include <string>
using namespace std; int main () {
vector <string*> numbers; // populate vector of pointers:
numbers.push_back ( new string ("one") );
numbers.push_back ( new string ("two") );
numbers.push_back ( new string ("three") );
numbers.push_back ( new string ("four") );
numbers.push_back ( new string ("five") ); vector <int> lengths ( numbers.size() ); transform (numbers.begin(), numbers.end(), lengths.begin(),MemFunction(&string::append,_1,"_test!").length()); for (int i=; i<; i++) {
cout << *numbers[i] << " has " << lengths[i] << " letters.\n";
}
return ;
}



最新文章

  1. JavaScript基本语法(三)
  2. [SharePoint 2010] 自定义字段类型开发(二)
  3. Mware vCenter Server 识别固态硬盘为(非SSD)是什么原因?
  4. 洛谷10月月赛Round.1| P3399 丝绸之路 [DP]
  5. C#调用c++Dll 结构体数组指针的问题
  6. Hibernate Criteria Restrictions
  7. 纸上谈兵:表(list)
  8. NIO提升系统性能
  9. 王家林 大数据Spark超经典视频链接全集[转]
  10. 【原】在一般处理程序中设置session
  11. http协议的各个版本及区别
  12. python官方文档
  13. MySQL 触发器例子(两张表同步增加和删除)
  14. eclipse提升注解提示速度
  15. SQLServer数据库操作
  16. 静态include与动态include的区别
  17. kill 结束进程
  18. PKUWC 2019 记
  19. eclipse如何加入第三方jar包
  20. python 全栈开发,Day88(csrf_exempt,ES6 快速入门,Vue)

热门文章

  1. Mac下在Shell终端下使用open快速打开窗口文件夹
  2. 第1章—Spring之旅—Spring模块介绍
  3. UTF8最好不要带BOM,附许多经典评论
  4. InnoDB的哈希算法
  5. InnoDB索引概述,二分查找法,平衡二叉树
  6. java数据结构---------插入排序的实现
  7. css3 响应式布局 Media Query
  8. 用户IP地址的三个属性的区别(HTTP_X_FORWARDED_FOR,HTTP_VIA,REM_addr)
  9. node错误集合
  10. 三:SQL server基础