Ecosyste.ms: Awesome

An open API service indexing awesome lists of open source software.

Awesome Lists | Featured Topics | Projects

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++

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.
```