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