Arene Base
Fundamental Utilities For Safety Critical C++
Loading...
Searching...
No Matches
variant_cast.hpp
Go to the documentation of this file.
1// Copyright 2026, Toyota Motor Corporation
2//
3// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
4
5// parasoft-suppress ALL "False Positive: there is no executable code on line 1"
6// parasoft-begin-suppress AUTOSAR-A2_8_1-a "False positive: this header intentionally defines both an implementation
7// class and variable template API."
8#ifndef INCLUDE_GUARD_ARENE_BASE_ARENE_BASE_VARIANT_VARIANT_CAST_HPP_
9#define INCLUDE_GUARD_ARENE_BASE_ARENE_BASE_VARIANT_VARIANT_CAST_HPP_
10// IWYU pragma: private, include "arene/base/variant.hpp"
11// IWYU pragma: friend "(arene/base(?!/tests)|stdlib/include/stdlib_detail)/.*"
12
13// parasoft-begin-suppress AUTOSAR-A16_2_2-a-2 "Arene Base aggregate headers permitted by A16-2-2 Permit #1"
15#include "arene/base/stdlib_choice/cstddef.hpp"
16#include "arene/base/stdlib_choice/cstdint.hpp"
17#include "arene/base/stdlib_choice/forward.hpp"
18#include "arene/base/stdlib_choice/initializer_list.hpp"
19#include "arene/base/stdlib_choice/integral_constant.hpp"
20#include "arene/base/stdlib_choice/is_constructible.hpp"
21#include "arene/base/stdlib_choice/is_same.hpp"
22#include "arene/base/stdlib_choice/numeric_limits.hpp"
23#include "arene/base/stdlib_choice/remove_cv.hpp"
24#include "arene/base/stdlib_choice/remove_reference.hpp"
25#include "arene/base/stdlib_choice/underlying_type.hpp"
32// parasoft-end-suppress AUTOSAR-A16_2_2-a-2
33
34namespace arene {
35namespace base {
36
37namespace variant_cast_detail {
38
39/// @brief Forward declaration of the type compatibility enum class. See @c type_compatibility for details.
40enum class type_compatibility : std::uint8_t;
41
42/// @brief Bit position of the explicit-conversion flag within @c type_compatibility.
43constexpr std::underlying_type_t<type_compatibility> explicit_conversion_bit{0U};
44/// @brief Bit position of the implicit-conversion flag within @c type_compatibility.
45constexpr std::underlying_type_t<type_compatibility> implicit_conversion_bit{1U};
46/// @brief Bit position of the exact-match flag within @c type_compatibility.
47constexpr std::underlying_type_t<type_compatibility> exact_match_bit{2U};
48
49//// @brief The type compatibility between two types for the purposes of determining if two type spaces are compatible.
50/// @note This is encoded as a bit map to avoid branches in the @c type_compatibility_v() function which cannot be
51/// covered since they're type-dependent not value dependent.
52enum class type_compatibility : std::uint8_t {
53
54 /// @brief The two types are incompatible
55 incompatible = 0b0000'0000U,
56 // parasoft-begin-suppress AUTOSAR-A5_1_1-a "False positive: literals are used to define the named constants"
57 // parasoft-begin-suppress AUTOSAR-M5_0_12-a "False positive: shift of uint8_t enumerator is intentional"
58 /// @brief The two types satisfy @c std::is_constructible<To,From>
59 explicit_conversion = 0b0000'0001U << explicit_conversion_bit,
60 /// @brief The two types satisfy @c is_implicitly_constructible<To,From>
61 implicit_conversion = 0b0000'0001U << implicit_conversion_bit,
62 /// @brief The two types satisfy @c std::is_same<From,To>
63 exact_match = 0b0000'0001U << exact_match_bit,
64 // parasoft-end-suppress AUTOSAR-M5_0_12-a
65 // parasoft-end-suppress AUTOSAR-A5_1_1-a
66};
67
68/// @brief The underlying type of @c type_compatibility, used for bitwise operations.
69using type_compatibility_bits = std::underlying_type_t<type_compatibility>;
70
71/// @brief Encodes a boolean value as a bit mask to be used in conjunction with @c type_compatibility_bits.
72/// @param compatibility The type compatibility to encode.
73/// @param has_compatibility A boolean value indicating whether the compatibility is present.
74/// @return The bit mask representation of the compatibility, or zero if not present.
75// parasoft-begin-suppress AUTOSAR-A7_1_5-a-2 "Trailing return syntax permitted by A7-1-5 Permit #1 v1.0.0"
76constexpr auto encode_type_compatibility(type_compatibility const compatibility, bool const has_compatibility) noexcept
77 -> type_compatibility_bits {
78 // parasoft-end-suppress AUTOSAR-A7_1_5-a-2
79 return has_compatibility ? static_cast<type_compatibility_bits>(compatibility) : 0U;
80}
81
82/// @brief Determine the type compatibility between two types.
83/// @tparam From The type to convert from. Should retain the same cvref qualification as the source variant.
84/// @tparam To The type to convert to. Should not be cref qualified.
85/// @return type_compatibility The type compatibility between @c From and @c To. The order of matching preference is
86/// exact match, implicit conversion, explicit conversion, incompatible.
87template <typename From, typename To>
88constexpr auto type_compatibility_v() noexcept -> type_compatibility_bits {
89 return encode_type_compatibility(type_compatibility::explicit_conversion, std::is_constructible<To, From>::value) |
90 encode_type_compatibility(type_compatibility::implicit_conversion, is_implicitly_constructible_v<To, From>) |
91 encode_type_compatibility(type_compatibility::exact_match, std::is_same<remove_cvref_t<From>, To>::value);
92}
93
94/// @brief Determine if a compatibility list contains a compatible type.
95/// @param compatibilities A list of type compatibilities between a source type and a list of target types.
96/// @param compatibility The type compatibility to check for.
97/// @return bool True if the compatibility list contains a compatible type, false otherwise.
98// parasoft-begin-suppress AUTOSAR-A7_1_5-a-2 "Trailing return syntax permitted by A7-1-5 Permit #1 v1.0.0"
99constexpr auto has_type_compatibility_v(
100 type_compatibility_bits const compatibilities,
101 type_compatibility const compatibility
102) noexcept -> bool {
103 // parasoft-end-suppress AUTOSAR-A7_1_5-a-2
104 return ((compatibilities & static_cast<type_compatibility_bits>(compatibility)) != 0U) ||
105 ((compatibility == type_compatibility::incompatible) && (compatibilities == 0U));
106}
107
108/// @brief A sentinel index of an incompatible type in a type space.
109/// @return The maximum value of @c std::size_t , used as a sentinel.
110// parasoft-begin-suppress AUTOSAR-A7_1_5-a-2 "Trailing return syntax permitted by A7-1-5 Permit #1 v1.0.0"
111constexpr auto incompatible_type_index() noexcept -> std::size_t { return std::numeric_limits<std::size_t>::max(); }
112// parasoft-end-suppress AUTOSAR-A7_1_5-a-2
113
114/// @brief Determine the index of the compatible type in a list of types given a list of type compatibilities.
115/// @param compatibilities A list of type compatibilities between a source type and a list of target types.
116/// @return std::size_t The index of the compatible type in the list of target types. If there is no compatible type, or
117/// if there is more than one compatible type and none are an exact match, then returns
118/// @c incompatible_type_index().
119// parasoft-begin-suppress AUTOSAR-A7_1_5-a-2 "Trailing return syntax permitted by A7-1-5 Permit #1 v1.0.0"
120constexpr auto index_of_compatible_type_v(std::initializer_list<type_compatibility_bits> const compatibilities) noexcept
121 -> std::size_t {
122 // parasoft-end-suppress AUTOSAR-A7_1_5-a-2
123 std::size_t current_index{0U};
124 std::size_t implicit_conversion_count{0U};
125 std::size_t explicit_conversion_count{0U};
126 std::size_t non_exact_match_index{incompatible_type_index()};
127 // parasoft-begin-suppress CERT_C-INT36-b "False positive: 'const type_compatibility*' not converted to integer"
128 // parasoft-begin-suppress AUTOSAR-A7_1_5-a "False positive: 'compatibility' has type deduced from range element"
129 for (auto const compatibility : compatibilities) {
130 // parasoft-end-suppress AUTOSAR-A7_1_5-a
131 // parasoft-end-suppress CERT_C-INT36-b
132 if (has_type_compatibility_v(compatibility, type_compatibility::exact_match)) {
133 return current_index;
134 }
135 if (has_type_compatibility_v(compatibility, type_compatibility::implicit_conversion)) {
136 ++implicit_conversion_count;
137 non_exact_match_index = current_index;
138 } else if (has_type_compatibility_v(compatibility, type_compatibility::explicit_conversion)) {
139 if (implicit_conversion_count == 0U) {
140 // if there was no implicit conversion, then this is the best match so far
141 non_exact_match_index = current_index;
142 }
143 ++explicit_conversion_count;
144 } else {
145 // empty clause required by M6-4-2, this means it's incompatible and nothing to mark
146 }
147 ++current_index;
148 }
149 // At this point either we returned already with an exact match, or non_exact_match has the index of the last implicit
150 // or explicit conversion match, or incompatible_type_index() if there were no matches.
151 // Therefore, if there is more than one implicit conversion match, or if there is no implicit conversion match and
152 // more than one explicit conversion match, then we have an ambiguous match and return incompatible_type_index().
153 if (implicit_conversion_count > 1U) {
154 return incompatible_type_index();
155 }
156 if ((implicit_conversion_count == 0U) && (explicit_conversion_count > 1U)) {
157 return incompatible_type_index();
158 }
159 return non_exact_match_index;
160}
161
162/// @brief Determine the index of the type in @c Tos that is compatible with @c From.
163/// @tparam From The type to convert from. Should retain the same cvref qualification as the source variant.
164/// @tparam Tos The types to convert to. Should not be cref qualified.
165/// @return std::size_t The index of the type in @c Tos that is compatible with @c From. If there is no compatible type,
166/// or if there is more than one compatible type and none are an exact match, then returns @c incompatible_type_index().
167template <typename From, typename... Tos>
168constexpr auto index_of_compatible_type_v() -> std::size_t {
169 return index_of_compatible_type_v(std::initializer_list<type_compatibility_bits>{type_compatibility_v<From, Tos>()...}
170 );
171}
172
173/// @brief Trait helper for SFINAE'ing on index of a compatible type. The empty base template for when it's not found.
174/// @tparam Idx The index of the compatible type in @c Tos. Should be the result of <c>index_of_compatible_type_v<From,
175/// Tos...>()</c>.
176// parasoft-begin-suppress AUTOSAR-A11_0_2-a "False positive: inheritance from integral_constant is permitted"
177template <std::size_t Idx, bool = (Idx < incompatible_type_index())>
178struct compatible_type_index_helper;
179
180/// @brief Specialization of @c compatible_type_index_helper for when a compatible type is found in @c Tos.
181/// @tparam Idx The index of the compatible type in @c Tos. Should be the result of <c>index_of_compatible_type_v<From,
182/// Tos...>()</c>.
183template <std::size_t Idx>
184struct compatible_type_index_helper<Idx, true> : std::integral_constant<std::size_t, Idx> {};
185
186/// @brief Trait for determining the index of the type in @c Tos that is compatible with @c From.
187/// @tparam From The type to convert from. Should retain the same cvref qualification as the source variant.
188/// @tparam Tos The types to convert to. Should not be cref qualified.
189template <typename From, typename... Tos>
190struct compatible_type_index : compatible_type_index_helper<index_of_compatible_type_v<From, Tos...>()> {};
191// parasoft-end-suppress AUTOSAR-A11_0_2-a
192
193/// @brief Empty base template of cast operation to hoist Tos... out of ToVariant
194/// @tparam ToVariant The variant type to cast to.
195template <typename ToVariant>
196class cast_impl;
197
198/// @brief Specialization of cast_impl for casting to a variant type.
199/// @tparam Tos The types that the variant can hold.
200template <typename... Tos>
201class cast_impl<variant<Tos...>> {
202 public:
203 /// @brief Cast a value of type @c From to a variant of type @c variant<Tos...> by constructing the value in place.
204 /// @tparam From The type to convert from.
205 /// @param from The value to convert from.
206 /// @return variant<Tos...> A variant of type @c variant<Tos...> containing the value from @c from .
207 // parasoft-begin-suppress AUTOSAR-M2_10_1-a-2 "Similar names permitted by M2-10-1 Permit #1"
208 template <typename From, typename CompatibleTypeIndex = compatible_type_index<From&&, Tos...>>
209 constexpr auto operator()(From&& from) const
210 noexcept(noexcept(variant<Tos...>{in_place_index<CompatibleTypeIndex::value>, std::forward<From>(from)}))
211 -> variant<Tos...> {
213 }
214 // parasoft-end-suppress AUTOSAR-M2_10_1-a-2
215};
216
217/// @brief Implementation of variant_cast function object.
218/// @tparam ToVariant The variant type to cast to.
219template <typename ToVariant>
220class variant_cast_fn {
221 static_assert(is_instantiation_of_v<ToVariant, variant>, "'ToVariant' must be a variant type");
222
223 public:
224 /// @brief Cast a variant to another variant type.
225 /// @tparam FromVariant The type of the variant to cast from.
226 /// @param from The variant to cast from.
227 /// @return ToVariant A variant of type @c ToVariant containing the value from @c from .
228 template <typename FromVariant>
229 auto operator()(FromVariant&& from) const
230 noexcept(noexcept(::arene::base::visit<ToVariant>(cast_impl<ToVariant>{}, std::forward<FromVariant>(from))))
231 -> ToVariant {
232 static_assert(is_instantiation_of_v<remove_cvref_t<FromVariant>, variant>, "'FromVariant' must be a variant type");
233 return ::arene::base::visit<ToVariant>(cast_impl<ToVariant>{}, std::forward<FromVariant>(from));
234 }
235};
236} // namespace variant_cast_detail
237
238// NOLINTNEXTLINE(google-build-namespaces) explicitly want per-TU instantiations
239// parasoft-begin-suppress AUTOSAR-M7_3_3-a "An unnamed namespace is used to create a per-TU reference to a global
240// object used in multiple TUs."
241// parasoft-begin-suppress CERT_CPP-DCL59-a "An unnamed namespace is used to create a per-TU reference to a global
242// object used in multiple TUs."
243namespace {
244// NOLINTBEGIN(cppcoreguidelines-avoid-non-const-global-variables) FP, there is no non-const global variable here.
245/// @brief Cast a variant to another variant type of a compatible type space.
246/// @tparam ToVariant The variant type to cast to. The type space of @c ToVariant must be compatible with the type space
247/// of the variant being cast from.
248/// @copydoc variant_cast_detail::variant_cast_fn<ToVariant>::operator()
249/// @note Casting to a variant with duplicate types is not supported until
250/// <c>variant(std::in_place_index_t<I>, Args&&...)</c> constructor is implemented.
251/// @details A compatible _type space_ is defined as follows: For every type <c>From...</c> in the source variant,
252/// there must be a type in <c>To...</c> which satisfies <c>std::is_constructible<To, From></c> where
253/// <c>From</c>'s cref qualification matches the source variant's. There must be a single unambiguously
254/// matched type in <c>To...</c> for every type in <c>From...</c>, where _unambiguously_ follows normal C++
255/// overload resolution rules.
256template <typename ToVariant>
257ARENE_MAYBE_UNUSED constexpr auto const& variant_cast = variant_cast_detail::variant_cast_fn<ToVariant>{};
258// NOLINTEND(cppcoreguidelines-avoid-non-const-global-variables)
259} // namespace
260// parasoft-end-suppress AUTOSAR-M7_3_3-a
261// parasoft-end-suppress CERT_CPP-DCL59-a
262
263} // namespace base
264} // namespace arene
265
266// parasoft-end-suppress AUTOSAR-A2_8_1-a
267
268#endif // INCLUDE_GUARD_ARENE_BASE_ARENE_BASE_VARIANT_VARIANT_CAST_HPP_
static constexpr value_type value
Definition integral_constant.hpp:34
static constexpr auto max() noexcept -> T
The maximum finite value.
Definition numeric_limits.hpp:230
Provides backports of std::in_place_t, std::in_place_type_t, and std::in_place_index_t from C++17.
#define ARENE_MAYBE_UNUSED
An alias for [[maybe_unused]] , or a no-op if the attribute is not supported.
Definition maybe_unused.hpp:25
Definition accumulate.hpp:37
constexpr bool is_instantiation_of_v
Definition is_instantiation_of.hpp:16
auto visit(VisitorT &&visitor, VariantT &&vrnt) noexcept(visit_detail::is_visitor_nothrow_invocable_r_v< visit_detail::visitor_invoke_result_t<, >,, >) -> visit_detail::visitor_invoke_result_t<, >
Invokes a given visitor with the active alternative in a given variant.
Definition visit.hpp:219
constexpr bool is_implicitly_constructible_v
Type trait to detect if a type is implicitly constructible from arguments of the specified types.
remove_cv_t< remove_reference_t< T > > remove_cvref_t
Backport of std::remove_cvref_t.
Definition remove_cvref.hpp:35
constexpr in_place_index_t< I > in_place_index
backport of std::in_place_index<T> from C++17
Definition accumulate.hpp:36
typename underlying_type< T >::type underlying_type_t
An alias for the underlying type of T, if T is an enumeration type.
Definition underlying_type.hpp:58
::uint8_t uint8_t
An 8-bit unsigned integer type.
Definition cstdint.hpp:30
::size_t size_t
A type suitable for holding the size of an object.
Definition cstddef.hpp:29
constexpr auto forward(remove_reference_t< T > &value) noexcept -> T &&
Cast a value to an rvalue if T is an rvalue or rvalue reference, otherwise forward an lvalue referenc...
Definition forward.hpp:24