fork download
  1. #include <functional>
  2.  
  3. template<class T, class RetType, class...Args>
  4. RetType CallMemFn(T* obj, RetType(T::*func)(Args...), Args...args)
  5. {return ((*obj).*(func))(std::forward<Args>(args)...);}
  6.  
  7. struct ConnectionHandle {};
  8.  
  9. template<class RetType, class...Args>
  10. ConnectionHandle connect(std::function<RetType(Args...)> func)
  11. {return {};}
  12.  
  13. template<class RetType, class...Args>
  14. ConnectionHandle connect(RetType(*func)(Args...))
  15. {return connect(std::function<RetType(Args...)>(func));}
  16.  
  17. template<class T, class RetType, class...Args>
  18. struct boundthis {
  19. typedef RetType result_type;
  20. typedef T* thistype;
  21. typedef RetType(*signature)(Args...);
  22. boundthis(T* self, RetType(T::*func)(Args...)) :self(self), func(func) {}
  23. RetType operator()(Args...args) {return CallMemFn(self,func,std::forward<Args>(args)...);}
  24. private:
  25. T* self;
  26. RetType(T::*func)(Args...);
  27. };
  28. template<class T, class RetType, class...Args>
  29. boundthis<T,RetType,Args...> bindthis(T* self, RetType(T::*func)(Args...))
  30. {return boundthis<T,RetType,Args...>(self, func);}
  31.  
  32. template<class T, class RetType, class...Args>
  33. ConnectionHandle connect(T* obj, RetType(T::*func)(Args...))
  34. {return connect(std::function<RetType(Args...)>(bindthis(obj, func)));}
  35.  
  36.  
  37. struct X
  38. {
  39. void memberFunction(int a, int b)
  40. {
  41. // do something
  42. }
  43. };
  44.  
  45. void globalStaticFunction(int a, int b)
  46. {
  47. // do something
  48. }
  49.  
  50.  
  51. int main()
  52. {
  53. // test instance
  54. X x;
  55.  
  56.  
  57. // connect a static function to the signal
  58. connect(&globalStaticFunction);
  59.  
  60. // connect a member function
  61. // here we have to use std::bind to get a std::function
  62. connect(&x, &X::memberFunction);
  63. }
Success #stdin #stdout 0s 3424KB
stdin
Standard input is empty
stdout
Standard output is empty