终于找到了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 @   EdenPei  阅读(15)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示