c++传递函数指针和bind的示例
时间:2021-06-18 18:34:38
#include <algorithm>
class TestClass
{
public:
int Sub(int x, int y) {
return y - x;
}
void InitAndTest() {
PrintWithClassMemberFunction(&TestClass::Sub);
PrintWithClassPointer(this);
}
// call: PrintWithClassMemberFunction(&TestClass::Sub);
void PrintWithClassMemberFunction(int (TestClass::*f)(int, int)) {
// add 'this' pointer
auto rel = (this->*f)(12, 13);
AtlTrace("[%d]\n", rel);
// bind with member function pointer into map
auto funBind = std::bind(f, this, std::placeholders::_1, std::placeholders::_2);
m_mapFun["PrintWithClassMemberFunction"] = funBind;
}
void PrintWithClassPointer(TestClass *pointInstance) {
auto rel = pointInstance->Sub(20, 30);
AtlTrace("[%d]\n", rel);
auto funBind = std::bind(&TestClass::Sub, pointInstance, std::placeholders::_1, std::placeholders::_2);
m_mapFun["PrintWithClassPointer"] = funBind;
}
void CallBindFun(int a, int b) {
std::for_each(
m_mapFun.begin(), m_mapFun.end(), [&a, &b](decltype(*m_mapFun.begin()) it) {
AtlTrace("[%s] %d\n", it.first.c_str(), it.second(a, b));
});
}
std::map<std::string, std::function<int (int, int)>> m_mapFun;
};
int _tmain(int argc, _TCHAR* argv[])
{
TestClass tc;
tc.InitAndTest();
tc.CallBindFun(64, 128);
}
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Java深入浅出数组的定义与使用下篇
![](https://img.aspxhome.com/file/2023/2/106132_0s.png)
解决spring boot启动扫描不到自定义注解的问题
SpringBoot2 整合Ehcache组件,轻量级缓存管理的原理解析
Volatile关键字的使用案例
![](https://img.aspxhome.com/file/2023/4/86054_0s.png)
mybatis批量添加,批量更新之前如何判断是否已经存在
![](https://img.aspxhome.com/file/2023/2/78962_0s.jpg)
Android SeekBar充当Progress实现兔兔进度条Plus
![](https://img.aspxhome.com/file/2023/5/106005_0s.png)
Java探索之Thread+IO文件的加密解密代码实例
springBoot整合rabbitMQ的方法详解
![](https://img.aspxhome.com/file/2023/8/70948_0s.png)
C#委托所蕴含的函数指针概念详细解析
java 正则,object中两个方法的使用(详解)
C#在复杂多线程环境下使用读写锁同步写入文件
![](https://img.aspxhome.com/file/2023/2/119602_0s.png)
Java 中HttpURLConnection附件上传的实例详解
Netty分布式pipeline管道创建方法跟踪解析
![](https://img.aspxhome.com/file/2023/0/58890_0s.png)
Android init.rc文件详解及简单实例
C#读取csv格式文件的方法
Java 方法签名详解及实例代码
c# 用ELMAH日志组件处理异常
![](https://img.aspxhome.com/file/2023/2/108672_0s.png)
Mybatis-Plus字段策略FieldStrategy的使用
![](https://img.aspxhome.com/file/2023/7/93077_0s.png)