当然,这是转自别人的: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 }
标签:function,解决办法,template,C++,Callback,static,func,函数指针,include From: https://www.cnblogs.com/edenpei/p/17396117.html