StormByte C++ Library 0.0.9999
StormByte is a comprehensive, cross-platform C++ library aimed at easing system programming, configuration management, logging, and database handling tasks. This library provides a unified API that abstracts away the complexities and inconsistencies of different platforms (Windows, Linux).
Loading...
Searching...
No Matches
expected.hxx
1#pragma once
2
3#include <StormByte/type_traits.hxx>
4
5#include <expected>
6#include <format>
7#include <type_traits>
8#include <memory>
9#include <string>
10
18namespace StormByte {
28 template <typename T, class E>
29 using Expected = std::conditional_t<
31 std::expected<std::reference_wrapper<std::remove_reference_t<T>>, std::shared_ptr<E>>,
32 std::expected<T, std::shared_ptr<E>>
33 >;
34
43 template <typename E>
44 auto Unexpected(std::shared_ptr<E> error_ptr) {
45 return std::unexpected<std::shared_ptr<E>>(std::move(error_ptr));
46 }
47
56 template <typename E>
57 auto Unexpected(E&& error) {
58 return std::unexpected<std::shared_ptr<std::decay_t<E>>>(
59 std::make_shared<std::decay_t<E>>(std::forward<E>(error))
60 );
61 }
62
70 template <typename Base, typename Derived>
71 auto Unexpected(Derived&& error) -> std::unexpected<std::shared_ptr<Base>>
72 requires std::is_base_of_v<Base, std::decay_t<Derived>>
73 {
74 using DerivedT = std::decay_t<Derived>;
75 return std::unexpected<std::shared_ptr<Base>>(std::static_pointer_cast<Base>(std::make_shared<DerivedT>(std::forward<Derived>(error))));
76 }
77
89 template <typename E, typename... Args>
90 auto Unexpected(const std::string& fmt, Args&&... args) {
91 std::string formatted_message;
92
93 if constexpr (sizeof...(Args) == 0) {
94 // No arguments provided, use the format string directly
95 formatted_message = fmt;
96 } else {
97 // Create lvalue references for all arguments
98 auto format_args = std::make_format_args(args...);
99
100 // Use std::vformat for runtime formatting
101 formatted_message = std::vformat(fmt, format_args);
102 }
103
104 // Construct the error instance with the formatted message
105 return std::unexpected<std::shared_ptr<E>>(
106 std::make_shared<E>(std::move(formatted_message))
107 );
108 }
109}
Concept to check if a type is a reference.
Definition type_traits.hxx:135
Main namespace for the StormByte library.
auto Unexpected(std::shared_ptr< E > error_ptr)
Creates an std::unexpected with a shared pointer to the error.
Definition expected.hxx:44
std::conditional_t< Type::Reference< T >, std::expected< std::reference_wrapper< std::remove_reference_t< T > >, std::shared_ptr< E > >, std::expected< T, std::shared_ptr< E > > > Expected
Expected type with support for reference types.
Definition expected.hxx:33