Skip to content

Commit 4189f08

Browse files
committed
is()/as(): Refactor is() and as() for std::any
1 parent 12c8a24 commit 4189f08

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
@@ -2060,28 +2060,22 @@ auto as( X&& x CPP2_SOURCE_LOCATION_PARAM_WITH_DEFAULT_AS) -> decltype(auto)
20602060

20612061
// is Type
20622062
//
2063-
template<typename T, typename X>
2064-
requires (std::is_same_v<X,std::any> && !std::is_same_v<T,std::any> && !std::is_same_v<T,empty>)
2065-
constexpr auto is( X const& x ) -> bool
2066-
{ return x.type() == Typeid<T>(); }
2067-
2068-
template<typename T, typename X>
2069-
requires (std::is_same_v<X,std::any> && std::is_same_v<T,empty>)
2070-
constexpr auto is( X const& x ) -> bool
2071-
{ return !x.has_value(); }
2072-
2063+
template<typename T, std::same_as<std::any> X>
2064+
constexpr auto is( X const& x ) -> bool{
2065+
if (!x.has_value()) {
2066+
return std::is_same_v<T,empty>;
2067+
}
2068+
return x.type() == Typeid<T>();
2069+
}
20732070

20742071
// is Value
20752072
//
20762073
inline constexpr auto is( std::any const& x, auto&& value ) -> bool
20772074
{
20782075
// Predicate case
2079-
if constexpr (requires{ bool{ value(x) }; }) {
2076+
if constexpr (valid_predicate<decltype(value), decltype(x)>) {
20802077
return value(x);
20812078
}
2082-
else if constexpr (std::is_function_v<decltype(value)> || requires{ &value.operator(); }) {
2083-
return false;
2084-
}
20852079

20862080
// Value case
20872081
else if constexpr (requires{ bool{ *std::any_cast<CPP2_TYPEOF(value)>(&x) == value }; }) {
@@ -2095,10 +2089,12 @@ inline constexpr auto is( std::any const& x, auto&& value ) -> bool
20952089

20962090
// as
20972091
//
2098-
template<typename T, typename X>
2099-
requires (!std::is_reference_v<T> && std::is_same_v<X,std::any> && !std::is_same_v<T,std::any>)
2100-
constexpr auto as( X const& x ) -> T
2101-
{ return std::any_cast<T>( x ); }
2092+
template<typename T, same_type_as<std::any> X>
2093+
constexpr auto as( X && x ) -> decltype(auto) {
2094+
constness_like_t<T, X>* ptr = std::any_cast<T>( &x );
2095+
if (!ptr) { Throw( std::bad_any_cast(), "'as' cast failed for 'std::any'"); }
2096+
return cpp2::forward_like<X>(*ptr);
2097+
}
21022098

21032099

21042100
//-------------------------------------------------------------------------------------------------------------

0 commit comments

Comments
 (0)