Loading...
Searching...
No Matches
result.hpp
Go to the documentation of this file.
1#pragma once
2
3#include <string>
4#include <variant>
5
6namespace terra::util {
7
8struct Ok
9{};
10
11template < typename T = Ok, typename E = std::string >
12class Result
13{
14 public:
15 // Success constructor
16 Result( T value )
17 : data( std::move( value ) )
18 {}
19
20 // Error constructor
22 : data( std::move( error ) )
23 {}
24
25 // Check if it's a success
26 [[nodiscard]] bool is_ok() const { return std::holds_alternative< T >( data ); }
27 [[nodiscard]] bool is_err() const { return std::holds_alternative< E >( data ); }
28
29 // Access value (call only if is_ok())
30 T& unwrap() { return std::get< T >( data ); }
31 const T& unwrap() const { return std::get< T >( data ); }
32
33 // Access error (call only if is_err())
34 E& error() { return std::get< E >( data ); }
35 const E& error() const { return std::get< E >( data ); }
36
37 // Return value or default if error
38 T unwrap_or( T default_value ) const { return is_ok() ? std::get< T >( data ) : default_value; }
39
40 // Transform the value if ok
41 template < typename Func >
42 auto map( Func f ) const -> Result< decltype( f( std::declval< T >() ) ), E >
43 {
44 if ( is_ok() )
45 return f( std::get< T >( data ) );
46 return std::get< E >( data );
47 }
48
49 private:
50 std::variant< T, E > data;
51};
52
53} // namespace terra::util
Definition result.hpp:13
bool is_err() const
Definition result.hpp:27
E & error()
Definition result.hpp:34
auto map(Func f) const -> Result< decltype(f(std::declval< T >())), E >
Definition result.hpp:42
T unwrap_or(T default_value) const
Definition result.hpp:38
T & unwrap()
Definition result.hpp:30
Result(E error)
Definition result.hpp:21
Result(T value)
Definition result.hpp:16
bool is_ok() const
Definition result.hpp:26
const E & error() const
Definition result.hpp:35
const T & unwrap() const
Definition result.hpp:31
Definition solver.hpp:9
Definition result.hpp:9