Skip to content

Repository files navigation

C++17 Result

Build Status

A Rust inspired Result<V,E> type for C++17.

template<typename V, typename E>
structResult;

basically a sophisticated wrapper for:

std::variant< ok<V>, error<E> >

Usage synopsis

autofn() -> Result<std::ifstream, string>;
autosplitLines(std::stringstream&) -> std::vector<string>;
intmain() {
auto f = openFile("hello.txt")
.orMap([](auto&&) { returnopenFile("fallback.txt"); }) // invoked only on error
.andMap([](auto&& in) -> Result<std::stringstream, string> { // invoked only if successful
std::stringstream out;
out << in.rdbuf();
if (out.str().empty()) returnerror("empty file"s);
returnok(move(out));
})
.andMap(&splitLines) // adds no errors
.orMap([](auto) -> Result<std::vector<string>, string> {
returnok(std::vector<string>{});
});
for (auto &l : f.unwrap()) std::cout << l << '\n'; // we are sure we have a value
}

see Result.test.cpp for a working example.

Requirements

You will need a C++17 compiler.

  • GCC 8.x
  • Clang 8.x + libc++
  • MSVC2017/2019
  • googletest is optional to run the tests

Links

Status

Even though this seems to work, it is only a proof of concept.

  • it works
  • std::variant is unusable slow for this kind of use case.
  • std::reference_wrapper does not allow comparisons.

About

A rust like Result type for modern C++

Topics

Resources

Stars

20 stars

Watchers

7 watching

Forks

Releases

Packages

Contributors

Languages