userver
C++ Async Framework
Toggle main menu visibility
Loading...
Searching...
No Matches
overloaded.hpp
Go to the documentation of this file.
1
#
pragma
once
2
3
/// @file userver/utils/overloaded.hpp
4
/// @brief @copybrief utils::Overloaded
5
6
#
include
<
type_traits
>
7
#
include
<
variant
>
8
9
USERVER_NAMESPACE_BEGIN
10
11
namespace
utils
{
12
13
/// @ingroup userver_universal
14
///
15
/// @brief Utility to define std::variant visitors in a simple way
16
template
<
class
... Ts>
17
struct
Overloaded
: Ts... {
// NOLINT(fuchsia-multiple-inheritance)
18
using
Ts::operator()...;
19
};
20
21
template
<
class
... Ts>
22
Overloaded(Ts...) ->
Overloaded
<Ts...>;
23
24
namespace
impl {
25
26
struct
DeduceVisitResult
final
{};
27
28
}
// namespace impl
29
30
/// @brief Calls the matching handler for the active alternative of @a var.
31
/// @tparam R Return type. If omitted, it is deduced from the handlers. If `void`, the handler result is discarded.
32
/// @param var Variant to visit.
33
/// @param ts Handlers combined into @ref utils::Overloaded.
34
/// @returns The selected handler result, converted to `R` when specified; nothing for `void` results.
35
template
<
class
R = impl::DeduceVisitResult,
class
... Args,
class
... Ts>
36
constexpr
decltype
(
auto
)
Visit
(
const
std::variant<Args...>& var, Ts&&... ts) {
37
if
constexpr
(std::is_same_v<R, impl::DeduceVisitResult>) {
38
return
std::visit(
Overloaded
{std::forward<Ts>(ts)...}, var);
39
}
else
{
40
return
std::visit<R>(
Overloaded
{std::forward<Ts>(ts)...}, var);
41
}
42
}
43
44
/// @overload
45
template
<
class
R = impl::DeduceVisitResult,
class
... Args,
class
... Ts>
46
constexpr
decltype
(
auto
)
Visit
(std::variant<Args...>& var, Ts&&... ts) {
47
if
constexpr
(std::is_same_v<R, impl::DeduceVisitResult>) {
48
return
std::visit(
Overloaded
{std::forward<Ts>(ts)...}, var);
49
}
else
{
50
return
std::visit<R>(
Overloaded
{std::forward<Ts>(ts)...}, var);
51
}
52
}
53
54
/// @overload
55
template
<
class
R = impl::DeduceVisitResult,
class
... Args,
class
... Ts>
56
constexpr
decltype
(
auto
)
Visit
(std::variant<Args...>&& var, Ts&&... ts) {
57
if
constexpr
(std::is_same_v<R, impl::DeduceVisitResult>) {
58
return
std::visit(
Overloaded
{std::forward<Ts>(ts)...}, std::move(var));
59
}
else
{
60
return
std::visit<R>(
Overloaded
{std::forward<Ts>(ts)...}, std::move(var));
61
}
62
}
63
64
}
// namespace utils
65
66
USERVER_NAMESPACE_END
userver
utils
overloaded.hpp
Generated on
for userver by
Doxygen
1.17.0