Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/rudifa/cpp-result
Create and use a Result class in C++
https://github.com/rudifa/cpp-result
Last synced: 7 days ago
JSON representation
Create and use a Result class in C++
- Host: GitHub
- URL: https://github.com/rudifa/cpp-result
- Owner: rudifa
- Created: 2024-12-12T20:08:47.000Z (2 months ago)
- Default Branch: main
- Last Pushed: 2024-12-12T20:11:02.000Z (2 months ago)
- Last Synced: 2024-12-21T19:17:44.158Z (2 months ago)
- Language: C++
- Size: 1.95 KB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# class Result
> A small exercise to create and use a Result class in C++, inspired by a similar class in Swift.
Most of the code was generated by perplexity.ai, in response to the prompt:
### rudifa
```
propose a C++ class Result that closely mimics the behaviour of the swift class Result; do not use exceptions
```### perplexity.ai
```
To mimic the behavior of Swift's Result class in C++ without using exceptions,we can create a template class that encapsulates either a success value or an error.
Here's a proposed implementation:
```> see Result.hpp
```
Key Features:This implementation closely mimics Swift's Result type:
Type Safety: It uses a template to allow any type for success (T) and error (E) values.
State Representation: It uses std::variant to store either a success value or an error.
Access Methods: It provides isSuccess() and isFailure() to check the state, and getValue() and getError() to access the contained values.
Transformation Methods: It includes map() and mapError() for transforming success and error values respectively, similar to Swift's implementation.
Usage Example:
Here's how you might use this Result class:
```
> see main.cpp
```
This implementation provides a type-safe way to handle operations that can fail,similar to Swift's Result type, without relying on exceptions.
It allows for clear error handling and supports functional-style transformations on the contained values.
```