Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Foo
- {
- public:
- Foo() {};
- ~Foo() {};
- void foo() { std::cout << "Hello from Foo:foo" << std::endl; }
- void bar(const int& i) { std::cout << "Hello from Foo:bar. i = " << i << std::endl; }
- int foobar(const int& i){ return i; }
- };
- template <typename function_t, typename object_t, typename... args_t>
- decltype(auto) safe_call(function_t _function, object_t* _object, args_t&&... _args)
- {
- if (_object != nullptr)
- return (_object->*_function)(std::forward<args_t>(_args)...);
- // throw std::exception("object is null"); // Commented
- }
- int main()
- {
- Foo* pobj2 = new Foo();
- Foo* pobj3 = nullptr;
- try
- {
- safe_call(&Foo::foo, pobj2);
- safe_call(&Foo::bar, pobj2, 2);
- std::cout << safe_call(&Foo::foobar, pobj2, 42) << std::endl;
- safe_call(&Foo::foo, pobj3); // Раз
- safe_call(&Foo::bar, pobj3, 3); // Два
- std::cout << safe_call(&Foo::foobar, pobj3, 42) << std::endl; // Три
- }
- catch (const std::exception& e)
- {
- std::cout << e.what() << std::endl;
- }
- system("pause");
- }
- template <typename function_t, typename object_t, typename... args_t>
- decltype(auto) safe_call(function_t _function, object_t* _object, args_t&&... _args)
- {
- if (_object != nullptr)
- return (_object->*_function)(std::forward<args_t>(_args)...);
- using R = typename std::result_of<function_t(object_t *, args_t...)>::type;
- return R();
- }
Add Comment
Please, Sign In to add comment