fork(1) download
  1. template <typename Type, typename ReturnType, typename MemFuncType>
  2. struct mem_fun_ptr_t
  3. {
  4. MemFuncType func;
  5. public:
  6. mem_fun_ptr_t(MemFuncType f) :
  7. func(f) {}
  8. ReturnType operator () (Type *p) const { return (p->*func)(); }
  9. };
  10.  
  11. // non-const version
  12. template <typename T, typename R>
  13. mem_fun_ptr_t<T, R, R (T::*)()> mem_fun_ptr(R (T::*Func)())
  14. {
  15. return mem_fun_ptr_t<T, R, R (T::*)()>(Func);
  16. }
  17.  
  18. // const version
  19. template <typename T, typename R>
  20. mem_fun_ptr_t<const T, R, R (T::*)() const> mem_fun_ptr(R (T::*Func)() const)
  21. {
  22. return mem_fun_ptr_t<const T, R, R (T::*)() const>(Func);
  23. }
  24.  
  25. #include <iostream>
  26. #include <string>
  27.  
  28. int main()
  29. {
  30. std::string str = "Hello";
  31. auto x = mem_fun_ptr(&std::string::length);
  32. std::cout << x(&str) << std::endl;
  33. const std::string const_str = str + ", world!";
  34. std::cout << x(&const_str) << std::endl;
  35. return 0;
  36. }
  37.  
Success #stdin #stdout 0s 2984KB
stdin
Standard input is empty
stdout
5
13