userver: userver/utils/overloaded.hpp Source File
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
9USERVER_NAMESPACE_BEGIN
10
11namespace utils {
12
13/// @ingroup userver_universal
14///
15/// @brief Utility to define std::variant visitors in a simple way
16template <class... Ts>
17struct Overloaded : Ts... { // NOLINT(fuchsia-multiple-inheritance)
18 using Ts::operator()...;
19};
20
21template <class... Ts>
22Overloaded(Ts...) -> Overloaded<Ts...>;
23
24namespace impl {
25
26struct 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.
35template <class R = impl::DeduceVisitResult, class... Args, class... Ts>
36constexpr 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
45template <class R = impl::DeduceVisitResult, class... Args, class... Ts>
46constexpr 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
55template <class R = impl::DeduceVisitResult, class... Args, class... Ts>
56constexpr 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
66USERVER_NAMESPACE_END