Skip to content

Commit 5ab0d84

Browse files
committed
is()/as(): Refactor is() and as() for std::any
1 parent d24510a commit 5ab0d84

File tree

1 file changed

+14
-18
lines changed

1 file changed

+14
-18
lines changed

include/cpp2util.h

+14-18
Original file line numberDiff line numberDiff line change
@@ -2045,28 +2045,22 @@ auto as( X&& x CPP2_SOURCE_LOCATION_PARAM_WITH_DEFAULT_AS) -> decltype(auto)
20452045

20462046
// is Type
20472047
//
2048-
template<typename T, typename X>
2049-
requires (std::is_same_v<X,std::any> && !std::is_same_v<T,std::any> && !std::is_same_v<T,empty>)
2050-
constexpr auto is( X const& x ) -> bool
2051-
{ return x.type() == Typeid<T>(); }
2052-
2053-
template<typename T, typename X>
2054-
requires (std::is_same_v<X,std::any> && std::is_same_v<T,empty>)
2055-
constexpr auto is( X const& x ) -> bool
2056-
{ return !x.has_value(); }
2057-
2048+
template<typename T, std::same_as<std::any> X>
2049+
constexpr auto is( X const& x ) -> bool{
2050+
if (!x.has_value()) {
2051+
return std::is_same_v<T,empty>;
2052+
}
2053+
return x.type() == Typeid<T>();
2054+
}
20582055

20592056
// is Value
20602057
//
20612058
inline constexpr auto is( std::any const& x, auto&& value ) -> bool
20622059
{
20632060
// Predicate case
2064-
if constexpr (requires{ bool{ value(x) }; }) {
2061+
if constexpr (valid_predicate<decltype(value), decltype(x)>) {
20652062
return value(x);
20662063
}
2067-
else if constexpr (std::is_function_v<decltype(value)> || requires{ &value.operator(); }) {
2068-
return false;
2069-
}
20702064

20712065
// Value case
20722066
else if constexpr (requires{ bool{ *std::any_cast<CPP2_TYPEOF(value)>(&x) == value }; }) {
@@ -2080,10 +2074,12 @@ inline constexpr auto is( std::any const& x, auto&& value ) -> bool
20802074

20812075
// as
20822076
//
2083-
template<typename T, typename X>
2084-
requires (!std::is_reference_v<T> && std::is_same_v<X,std::any> && !std::is_same_v<T,std::any>)
2085-
constexpr auto as( X const& x ) -> T
2086-
{ return std::any_cast<T>( x ); }
2077+
template<typename T, same_type_as<std::any> X>
2078+
constexpr auto as( X && x ) -> decltype(auto) {
2079+
constness_like_t<T, X>* ptr = std::any_cast<T>( &x );
2080+
if (!ptr) { Throw( std::bad_any_cast(), "'as' cast failed for 'std::any'"); }
2081+
return cpp2::forward_like<X>(*ptr);
2082+
}
20872083

20882084

20892085
//-------------------------------------------------------------------------------------------------------------

0 commit comments

Comments
 (0)