【tmp post】about c++ std::function

C++成员函数指针与std::function用法
本文介绍C++中如何使用成员函数指针及std::function来传递成员函数。通过示例展示了定义成员函数指针类型、使用指向成员函数的指针调用对象方法的过程,并演示了C++11中std::function的应用。

2017-12-29

 1 // see file functional: class function<_Res(_ArgTypes...)>
 2 template<typename T>
 3 class foo;
 4 
 5 template<typename T1, typename T2>
 6 class foo<T1(T2)> {
 7 public:
 8         T1 i1;
 9         T2 i2;
10 };

 

https://stackoverflow.com/questions/2402579/function-pointer-to-member-function

https://stackoverflow.com/questions/12662891/passing-a-member-function-as-an-argument-in-c

example

 1 #include <iostream>
 2 #include <functional>
 3 
 4 using namespace std;
 5 
 6 class CLS
 7 {
 8 public:
 9     int i_;
10     CLS(int i):i_(i) {}
11     void method(const string& id) { cout << i_ << ": " << id << endl; }
12 };
13 
14 typedef void (CLS::*FUNC_PTR)(const string&);
15 
16 void foo(CLS& obj, FUNC_PTR method)
17 {
18     (obj.*method)("by function pointer");
19 }
20 
21 int main()
22 {
23     CLS cls0(0);
24     FUNC_PTR fp = &CLS::method; //err: &(CLS::method)
25     foo(cls0, fp);
26 
27     //C++11
28     CLS cls1(1);
29     function<void(CLS*, const string&)> f = &CLS::method;
30     f(&cls1, "by std::function");
31     
32     return 0;
33 }

 

转载于:https://www.cnblogs.com/albumcover/p/8146267.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值