Skip to content

Commit d9ee8da

Browse files
committed
is()/as(): Refactor is() and as() for std::any
1 parent def893c commit d9ee8da

File tree

1 file changed

+14
-18
lines changed

1 file changed

+14
-18
lines changed

include/cpp2util.h

Lines changed: 14 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -2083,28 +2083,22 @@ auto as(X&& x CPP2_SOURCE_LOCATION_PARAM_WITH_DEFAULT_AS) -> decltype(auto)
20832083

20842084
// is Type
20852085
//
2086-
template<typename T, typename X>
2087-
requires (std::is_same_v<X,std::any> && !std::is_same_v<T,std::any> && !std::is_same_v<T,empty>)
2088-
constexpr auto is( X const& x ) -> bool
2089-
{ return x.type() == Typeid<T>(); }
2090-
2091-
template<typename T, typename X>
2092-
requires (std::is_same_v<X,std::any> && std::is_same_v<T,empty>)
2093-
constexpr auto is( X const& x ) -> bool
2094-
{ return !x.has_value(); }
2095-
2086+
template<typename T, std::same_as<std::any> X>
2087+
constexpr auto is( X const& x ) -> bool{
2088+
if (!x.has_value()) {
2089+
return std::is_same_v<T,empty>;
2090+
}
2091+
return x.type() == Typeid<T>();
2092+
}
20962093

20972094
// is Value
20982095
//
20992096
inline constexpr auto is( std::any const& x, auto&& value ) -> bool
21002097
{
21012098
// Predicate case
2102-
if constexpr (requires{ bool{ value(x) }; }) {
2099+
if constexpr (valid_predicate<decltype(value), decltype(x)>) {
21032100
return value(x);
21042101
}
2105-
else if constexpr (std::is_function_v<decltype(value)> || requires{ &value.operator(); }) {
2106-
return false;
2107-
}
21082102

21092103
// Value case
21102104
else if constexpr (requires{ bool{ *std::any_cast<CPP2_TYPEOF(value)>(&x) == value }; }) {
@@ -2118,10 +2112,12 @@ inline constexpr auto is( std::any const& x, auto&& value ) -> bool
21182112

21192113
// as
21202114
//
2121-
template<typename T, typename X>
2122-
requires (!std::is_reference_v<T> && std::is_same_v<X,std::any> && !std::is_same_v<T,std::any>)
2123-
constexpr auto as( X const& x ) -> T
2124-
{ return std::any_cast<T>( x ); }
2115+
template<typename T, same_type_as<std::any> X>
2116+
constexpr auto as( X && x ) -> decltype(auto) {
2117+
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+
return cpp2::forward_like<X>(*ptr);
2120+
}
21252121

21262122

21272123
//-------------------------------------------------------------------------------------------------------------

0 commit comments

Comments
 (0)