fork download
  1. #include <utility>
  2. #include <cassert>
  3.  
  4.  
  5. template<typename T, typename R, typename ...Args>
  6. class mem_fun_t {
  7.  
  8. using method_ptr_t = R (T::*)(Args...);
  9.  
  10. public:
  11. mem_fun_t(method_ptr_t const methodPtr_) : methodPtr_(methodPtr_) {
  12. assert(methodPtr_);
  13. }
  14.  
  15. R operator ()(T * const objectPtr, Args && ...args) const {
  16. assert(objectPtr);
  17. return (objectPtr->*methodPtr_)(std::forward<Args>(args)...);
  18. }
  19.  
  20. R operator ()(T & objectRef, Args && ...args) const {
  21. return (objectRef.*methodPtr_)(std::forward<Args>(args)...);
  22. }
  23.  
  24. private:
  25. method_ptr_t const methodPtr_;
  26. };
  27.  
  28. template<typename T, typename R, typename ...Args>
  29. mem_fun_t<T, R, Args...> mem_fun(R (T::*pointer)(Args...)) {
  30. return {pointer};
  31. }
  32.  
  33. template<typename T, typename R, typename ...Args>
  34. mem_fun_t<T const, R, Args...> mem_fun(R (T::*pointer)(Args...) const) {
  35. return {pointer};
  36. }
  37.  
  38.  
  39. struct test {
  40.  
  41. int mutable_method(float f, double d) {
  42. return static_cast<int>(f + d);
  43. }
  44.  
  45. int const_method(float f, double d) const {
  46. return static_cast<int>(f + d);
  47. }
  48. };
  49.  
  50.  
  51. int main() {
  52. test mutableObject;
  53. test const constObject;
  54.  
  55. auto const mutableBinded = mem_fun(&test::mutable_method);
  56. assert(mutableBinded(&mutableObject, 5.56f, 7.91) == 13);
  57. assert(mutableBinded(mutableObject, 78.9f, 1.2) == 80);
  58.  
  59. auto const constBinded = mem_fun(&test::const_method);
  60. assert(constBinded(&mutableObject, 4.51f, 13.6) == 18);
  61. assert(constBinded(&constObject, -123.1f, 45.5) == -77);
  62. assert(constBinded(mutableObject, -98.f, 56.4) == -41);
  63. assert(constBinded(constObject, 45.56f, 45.5) == 91);
  64. }
  65.  
Success #stdin #stdout 0s 2892KB
stdin
Standard input is empty
stdout
Standard output is empty