A C++17 Library for generic type queries or conversions, based on Herb Sutter's talk at CPPCon 2021
#include <cpp_as_is/cpp_as_is.hpp>
int main() {
using namespace cpp_as_is;
auto someWrappedValue = getValue<int>();
if (is<int>(someWrappedValue)) {
int value = as<int>(someWrappedValue);
std::cout << "value: " << value << '\n';
} else {
std::cout << "No value";
}
return 0;
}
NB: All specializations and overloads are conditionally present using __has_include
directives
Legend: to means both is
and as
are available, is means only is
is available
T
toT
T*
toT
T*
isstd::nullptr_t
T*
toU*
std::any
toT
boost::any
toT
std::expected<T, ...>
toT
std::expected<T, E>
tostd::unexpected<E>
BOOST_OUTCOME_V2_NAMESPACE::outcome<T, ...>
toT
BOOST_OUTCOME_V2_NAMESPACE::outcome<T, ErrCode, ...>
toErrCode
BOOST_OUTCOME_V2_NAMESPACE::outcome<T, ErrCode, ExcPtr, ...>
toExcPtr
BOOST_OUTCOME_V2_NAMESPACE::result<T, ...>
toT
BOOST_OUTCOME_V2_NAMESPACE::result<T, ErrCode, ...>
toErrCode
std::future<T>
toT
std::optional<T>
toT
std::optional<T>
isstd::nullopt_t
boost::optional<T>
toT
std::shared_ptr<T>
toT
std::unique_ptr<T>
toT
std::variant<Variants...>
toT
There are two extension points:
cpp_as_is::ext::is_conversion_traits<From, To>
forcpp_as_is::is<To>(from)
, as described by thecpp_as_is::InspectableWithIs<From, To>
conceptarg_type
represents the expected argument type when callingis
static inline bool matches(const arg_type &) noexcept
is the static member function that checks whether the types "match" (it should be constexpr if possible, though it's not required)
cpp_as_is::ext::as_conversion_traits<From, To>
forcpp_as_is::as<To>(from)
, as described by thecpp_as_is::IsConvertibleWithAs<From, To>
conceptarg_type
represents the expected argument type when callingas
return_type
represents the expected return type ofas
static inline return_type convert(arg_type) noexcept
is the static member function that handles converting fromFrom
toTo
As a rule:
- if you're going to extend
as
, you must first extendis
- provide as many overloads for
as_conversion_traits::convert
as possible (e.g. const ref, rvalue, etc...)