终于找到了C++成员函数做函数指针的完美解决办法

当然,这是转自别人的:https://www.codenong.com/19808054/

之前因为这个没少废精力啊,这里记一下,感谢外国友人的回答.

 1 #include <iostream>
 2 #include <functional>
 3 #include <string>
 4 #include <sstream>
 5 #include <memory>
 6 
 7 using namespace std;
 8 
 9 template <typename T>
10 struct Callback;
11 
12 template <typename Ret, typename... Params>
13 struct Callback<Ret(Params...)>
14 {
15     template <typename... Args>
16     static Ret callback(Args... args) { return func(args...); }
17     static function<Ret(Params...)> func;
18 };
19 
20 // Initialize the static member.
21 template <typename Ret, typename... Params>
22 function<Ret(Params...)> Callback<Ret(Params...)>::func;
23 
24 class Foo
25 {
26 public:
27     void print(int* x) { // Some member function.
28         cout << *x << endl;
29     }
30 };
31 
32 typedef  void (*cFunc)(int*);
33 
34 int main()
35 {
36     Foo foo; // Create instance of Foo.
37     // Store member function and the instance using bind.
38     Callback<void(int*)>::func = bind(&Foo::print, foo, placeholders::_1);
39 
40     // Convert callback-function to c-pointer.
41     cFunc c_func = static_cast<decltype(c_func)>(Callback<void(int*)>::callback);
42 
43     // Use in any way you wish.
44     unique_ptr<int> iptr{new int(5)};
45     c_func(iptr.get());
46 
47     int data = 10;
48     c_func(&data);
49 }

 

posted @ 2023-05-12 19:23  EdenPei  阅读(27)  评论(0)    收藏  举报