Skip to content

Commit 016f9ed

Browse files
committed
as(): make as() cast to use type_safety.enforce
The current implementation for std::any, std::optional, and std::variant throws exceptions. This behaviour is inconsistent to runtime checked as() for signed/unsigned integral cast. This implementation allows to setup one approch for type_safety issues. Current behaviour is to terminate but it can be changed to e.g. throwing exception.
1 parent fb5e13b commit 016f9ed

File tree

1 file changed

+4
-3
lines changed

1 file changed

+4
-3
lines changed

include/cpp2util.h

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -908,6 +908,7 @@ class contract_group {
908908

909909
constexpr contract_group (handler h = {}) : reporter{h} { }
910910
constexpr auto set_handler(handler h = {}) { reporter = h; }
911+
constexpr auto get_handler() const -> handler { return reporter; }
911912
constexpr auto is_active () const -> bool { return reporter != handler{}; }
912913

913914
constexpr auto enforce(bool b, CPP2_MESSAGE_PARAM msg = "" CPP2_SOURCE_LOCATION_PARAM_WITH_DEFAULT)
@@ -2073,7 +2074,7 @@ auto as(X&& x CPP2_SOURCE_LOCATION_PARAM_WITH_DEFAULT_AS) -> decltype(auto)
20732074
if constexpr (std::is_same_v< typename It::type, C >) { if (CPP2_FORWARD(x).index() == It::index) { ptr = &std::get<It::index>(x); return true; } };
20742075
return false;
20752076
});
2076-
if (!ptr) { Throw( std::bad_variant_access(), "'as' cast failed for 'variant'"); }
2077+
type_safety.enforce(ptr, "'as' cast failed for 'variant'");
20772078
return cpp2::forward_like<decltype(x)>(*ptr);
20782079
}
20792080

@@ -2115,7 +2116,7 @@ inline constexpr auto is( std::any const& x, auto&& value ) -> bool
21152116
template<typename T, same_type_as<std::any> X>
21162117
constexpr auto as( X && x ) -> decltype(auto) {
21172118
constness_like_t<T, X>* ptr = std::any_cast<T>( &x );
2118-
if (!ptr) { Throw( std::bad_any_cast(), "'as' cast failed for 'std::any'"); }
2119+
type_safety.enforce(ptr, "'as' cast failed for 'std::any'");
21192120
return cpp2::forward_like<X>(*ptr);
21202121
}
21212122

@@ -2165,7 +2166,7 @@ constexpr auto as( X&& x ) -> decltype(auto) {
21652166
ptr = &static_cast<constness_like_t<T, X>&>(*x);
21662167
}
21672168
}
2168-
if (!ptr) { Throw( std::bad_optional_access(), "'as' cast failed for 'std::optional'"); }
2169+
type_safety.enforce(ptr, "'as' cast failed for 'std::optional'");
21692170
return cpp2::forward_like<X>(*ptr);
21702171
}
21712172

0 commit comments

Comments
 (0)