Guest User

Untitled

a guest
Nov 14th, 2018
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.43 KB | None | 0 0
  1. class Foo
  2. {
  3. public:
  4. Foo() {};
  5. ~Foo() {};
  6. void foo() { std::cout << "Hello from Foo:foo" << std::endl; }
  7. void bar(const int& i) { std::cout << "Hello from Foo:bar. i = " << i << std::endl; }
  8. int foobar(const int& i){ return i; }
  9. };
  10.  
  11. template <typename function_t, typename object_t, typename... args_t>
  12. decltype(auto) safe_call(function_t _function, object_t* _object, args_t&&... _args)
  13. {
  14. if (_object != nullptr)
  15. return (_object->*_function)(std::forward<args_t>(_args)...);
  16.  
  17. // throw std::exception("object is null"); // Commented
  18. }
  19.  
  20. int main()
  21. {
  22. Foo* pobj2 = new Foo();
  23. Foo* pobj3 = nullptr;
  24.  
  25. try
  26. {
  27. safe_call(&Foo::foo, pobj2);
  28. safe_call(&Foo::bar, pobj2, 2);
  29. std::cout << safe_call(&Foo::foobar, pobj2, 42) << std::endl;
  30.  
  31. safe_call(&Foo::foo, pobj3); // Раз
  32. safe_call(&Foo::bar, pobj3, 3); // Два
  33. std::cout << safe_call(&Foo::foobar, pobj3, 42) << std::endl; // Три
  34. }
  35. catch (const std::exception& e)
  36. {
  37. std::cout << e.what() << std::endl;
  38. }
  39.  
  40. system("pause");
  41. }
  42.  
  43. template <typename function_t, typename object_t, typename... args_t>
  44. decltype(auto) safe_call(function_t _function, object_t* _object, args_t&&... _args)
  45. {
  46. if (_object != nullptr)
  47. return (_object->*_function)(std::forward<args_t>(_args)...);
  48.  
  49. using R = typename std::result_of<function_t(object_t *, args_t...)>::type;
  50. return R();
  51. }
Add Comment
Please, Sign In to add comment