i want create template should wrap it's parameter. parameter should arbitrary function call, gets wrapped via template metaprogramming magic prefix , postfix code.
i want use follows:
auto result = try_call( some_vector.at(13) ); and try_call defined somehow wraps try..catch block around some_vector.at(13). this:
template<typename t> // template metaprogramming magic here try { auto value = // execute parameter here, i.e. some_vector.at(13); return std::experimental::optional<t>(value); } catch (std::exception&) { return std::experimental::nullopt; } there paper of bjarne stroustrup, that's not describing need, , wasn't able find solution problem.
if isn't possible directly, thinking of doing via templated function taking lambda:
template<typename func> auto try_call(func f) { try { return f(); } catch(std::exception&) { return std::experimental::nullopt; } } but don't know if that's idea. lambda has overhead, guess? want avoid unneccessary overhead.
actually, solution lambda quite , efficient. type theoretic point of view, try_call higher order function: takes argument function , executes in try catch context.
template<typename func> auto try_call(func f) -> std::experimental::optional<std::decay_t<decltype(f())>> { try { return std::experimental::make_optional(f()); } catch(std::exception&) { return std::experimental::nullopt; } } calling lambda yield want without overhead. lambda compiled anonymous struct overloaded function call operator. struct used template parameter try_call function. therefore, compiler knows function executed when calling f() , inlined. no overhead involved.
Comments
Post a Comment