open62541pp 0.17.0
C++ wrapper of open62541
Loading...
Searching...
No Matches
result_utils.hpp
Go to the documentation of this file.
1#pragma once
2
3#include <functional> // invoke
4#include <type_traits> // invoke_result_t
5
7
8namespace opcua::detail {
9
10// Derive Result type from T
11template <typename T>
12struct ResultType {
13 using Type = opcua::Result<T>;
14};
15
16template <>
17struct ResultType<StatusCode> {
18 using Type = opcua::Result<void>;
19};
20
21template <>
22struct ResultType<BadResult> {
23 using Type = opcua::Result<void>;
24};
25
26/**
27 * Invoke a function and capture its Result (value or status code).
28 * This is especially useful for C-API callbacks, that are executed within the open62541 event loop.
29 */
30template <typename F, typename... Args>
31auto tryInvoke(F&& func, Args&&... args) noexcept ->
32 typename ResultType<std::invoke_result_t<F, Args...>>::Type {
33 using ReturnType = std::invoke_result_t<F, Args...>;
34 try {
35 if constexpr (std::is_void_v<ReturnType>) {
36 std::invoke(std::forward<F>(func), std::forward<Args>(args)...);
37 return {};
38 } else {
39 return std::invoke(std::forward<F>(func), std::forward<Args>(args)...);
40 }
41 } catch (...) {
42 return BadResult(getStatusCode(std::current_exception()));
43 }
44}
45
46} // namespace opcua::detail
The template class Result encapsulates a StatusCode and optionally a value.
Definition result.hpp:53