Demonstrates C++20 concepts for type-safe generic programming.
Demonstrates C++20 concepts for type-safe generic programming.Shows Resultable, Unwrappable, MonadicResult, and other concepts used to constrain template parameters throughout the ecosystem.
#include <iostream>
#include <string>
#include <type_traits>
template <concepts::Resultable R>
{
std::cout << " " << label << ": "
<< (result.is_ok() ? "OK" : "ERROR") << "\n";
}
template <typename T>
{
}
template <concepts::MonadicResult R>
{
return result
.map([](const auto& v) { return v * 2; })
.map([](const auto& v) { return v + 10; });
}
template <typename T>
{
if constexpr (concepts::Resultable<T>)
{
std::cout << " Processing Result type: "
<< (value.is_ok() ? "success" : "failure") << "\n";
}
else
{
std::cout << " Processing non-Result type: " << value << "\n";
}
}
{
std::cout << "=== C++20 Concepts Showcase ===\n\n";
std::cout << "1. Resultable concept:\n";
auto failure = make_error<int>(error_codes::INVALID_ARGUMENT, "bad input", "demo");
static_assert(concepts::Resultable<Result<int>>,
"Result<int> must satisfy Resultable");
std::cout << " static_assert: Result<int> is Resultable\n";
std::cout << "\n2. Unwrappable concept:\n";
std::cout << " safe_unwrap(ok(42), -1) = " << val << "\n";
std::cout << " safe_unwrap(error, -1) = " << val2 << "\n";
std::cout << "\n3. MonadicResult concept:\n";
if (chained.is_ok())
{
std::cout << " transform_chain(ok(5)): 5 * 2 + 10 = " << chained.value() << "\n";
}
make_error<int>(error_codes::INTERNAL_ERROR, "oops", "demo"));
std::cout << " transform_chain(error): is_ok = "
<< (chained_err.is_ok() ? "true" : "false") << "\n";
std::cout << "\n4. Concept-based dispatch:\n";
std::cout << "\n5. Compile-time type traits:\n";
std::cout << " Result<int> is Resultable: "
<< concepts::Resultable<Result<int>> << "\n";
std::cout << " Result<int> is Mappable: "
<< concepts::Mappable<Result<int>> << "\n";
std::cout << " int is Resultable: "
<< concepts::Resultable<int> << "\n";
std::cout << "\nDone.\n";
return 0;
}
Result type for error handling with member function support.
T unwrap_or(T default_value) const
Get value or return default.
Core C++20 concepts for Result/Optional types.
auto transform_chain(R result)
void process(const T &value)
T safe_unwrap(const Result< T > &val, const T &fallback)
void inspect_result(const R &result, const std::string &label)
Result< T > ok(T value)
Create a successful result.
Umbrella header for Result<T> type and related utilities.