Skip to content

Instantly share code, notes, and snippets.

@Vaiz
Created July 15, 2022 08:15
Show Gist options
  • Save Vaiz/057cface48d5bb9f399c23d4235d23aa to your computer and use it in GitHub Desktop.
Save Vaiz/057cface48d5bb9f399c23d4235d23aa to your computer and use it in GitHub Desktop.
use boost::outcome as an alternative to std::expected
// https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2021/p0323r11.html
// https://en.cppreference.com/w/cpp/header/expected
// https://www.boost.org/doc/libs/master/libs/outcome/doc/html/index.html
// https://github.com/TartanLlama/expected
#include <boost/outcome.hpp>
template <typename T>
using expected = boost::outcome_v2::result<T, std::exception_ptr>;
template <typename Exception>
std::exception_ptr makeUnexpected(const Exception& e)
{
return std::make_exception_ptr(e);
}
expected<int> Test(bool cond)
{
if (cond)
return 1;
else
return makeUnexpected(std::runtime_error("test error"));
// return std::make_exception_ptr(std::runtime_error("test error"));
}
int main(int argc, char *argv[])
{
try {
auto result1 = Test(true);
std::cout << "has error: " << result1.has_error() << std::endl;
std::cout << result1.value() << std::endl;
auto result2 = Test(false);
std::cout << "has error: " << result2.has_error() << std::endl;
std::cout << result2.value() << std::endl;
} catch (std::exception& e) {
std::cerr << "Exception: " << e.what() << std::endl;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment