Skip to content

Commit a63718e

Browse files
committed
is()/as(): Refactor is() and as() for std::any
1 parent 330e225 commit a63718e

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
@@ -2082,28 +2082,22 @@ auto as(specialization_of_template<std::variant> auto&& x CPP2_SOURCE_LOCATION_P
20822082

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

20962093
// is Value
20972094
//
20982095
inline constexpr auto is( std::any const& x, auto&& value ) -> bool
20992096
{
21002097
// Predicate case
2101-
if constexpr (requires{ bool{ value(x) }; }) {
2098+
if constexpr (valid_predicate<decltype(value), decltype(x)>) {
21022099
return value(x);
21032100
}
2104-
else if constexpr (std::is_function_v<decltype(value)> || requires{ &value.operator(); }) {
2105-
return false;
2106-
}
21072101

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

21182112
// as
21192113
//
2120-
template<typename T, typename X>
2121-
requires (!std::is_reference_v<T> && std::is_same_v<X,std::any> && !std::is_same_v<T,std::any>)
2122-
constexpr auto as( X const& x ) -> T
2123-
{ return std::any_cast<T>( x ); }
2114+
template<typename T, same_type_as<std::any> X>
2115+
constexpr auto as( X && x ) -> decltype(auto) {
2116+
constness_like_t<T, X>* ptr = std::any_cast<T>( &x );
2117+
if (!ptr) { Throw( std::bad_any_cast(), "'as' cast failed for 'std::any'"); }
2118+
return cpp2::forward_like<X>(*ptr);
2119+
}
21242120

21252121

21262122
//-------------------------------------------------------------------------------------------------------------

0 commit comments

Comments
 (0)