【tmp post】about c++ 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 }

 

posted @ 2017-12-29 20:47  AlbumCover  阅读(192)  评论(0编辑  收藏  举报