Skip to content

Voltra/cpp-as-is

Repository files navigation

cpp-as-is

ci codecov CodeQL

About cpp-as-is

A C++17 Library for generic type queries or conversions, based on Herb Sutter's talk at CPPCon 2021

Usage

#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;
}

Available conversions & queries

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

Extendability

There are two extension points:

  • cpp_as_is::ext::is_conversion_traits<From, To> for cpp_as_is::is<To>(from), as described by the cpp_as_is::InspectableWithIs<From, To> concept
    • arg_type represents the expected argument type when calling is
    • 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> for cpp_as_is::as<To>(from), as described by the cpp_as_is::IsConvertibleWithAs<From, To> concept
    • arg_type represents the expected argument type when calling as
    • return_type represents the expected return type of as
    • static inline return_type convert(arg_type) noexcept is the static member function that handles converting from From to To

As a rule:

  • if you're going to extend as, you must first extend is
  • provide as many overloads for as_conversion_traits::convert as possible (e.g. const ref, rvalue, etc...)

More Details

About

A C++17 Library for generic type queries or conversions, based on Herb Sutter's talk at CPPCon 2021 (https://www.youtube.com/watch?v=raB_289NxBk)

Topics

Resources

Stars

Watchers

Forks

Packages

No packages published