Skip to content

A minimal std::expected<T, E> #12

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
fixup: Add operator* observers
  • Loading branch information
deanberris committed Feb 1, 2019
commit bf4bd0b439e50adddcf370567c1b994453dcdda2
46 changes: 45 additions & 1 deletion netlib/expected.h
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,31 @@ struct unexpect_t {
inline constexpr unexpect_t unexpect{};

template <class E>
class bad_expected_access {};
class bad_expected_access;

template <>
class bad_expected_access<void> {
public:
virtual const char* what() const noexcept {
return "cppnetlib::bad_expected_access";
}
virtual ~bad_expected_access() {}
};

template <class E>
class bad_expected_access : public bad_expected_access<void> {
public:
explicit bad_expected_access(E e) : val_(e) {}
const char* what() const noexcept override {
return "cppnetlib::bad_expected_access<E>";
}
const E& error() const&;
E& error() &;
E&& error() &&;

private:
E val_;
};

/// This is a minimal implementation of the proposed P0323R3
/// std::expected<...> API.
Expand Down Expand Up @@ -208,6 +232,26 @@ class expected {
constexpr explicit operator bool() const noexcept { return has_value_; }

// Observer functions.
constexpr const T& operator*() const& {
if (!has_value_) throw bad_expected_access<E>(error());
return *reinterpret_cast<const T*>(&union_storage_);
}

constexpr T& operator*() & {
if (!has_value_) throw bad_expected_access<E>(error());
return *reinterpret_cast<T*>(&union_storage_);
}

constexpr const T&& operator*() const&& {
if (!has_value_) throw bad_expected_access<E>(error());
return std::move(*reinterpret_cast<const T*>(&union_storage_));
}

constexpr T&& operator*() && {
if (!has_value_) throw bad_expected_access<E>(error());
return std::move(*reinterpret_cast<T*>(&union_storage_));
}

constexpr const E& error() const& {
assert(!has_value_ &&
"expected<T, E> must not have a value when taking an error!");
Expand Down
1 change: 1 addition & 0 deletions netlib/expected_test.cc
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ TEST(ExpectedTest, Unexpected) {

auto e2 = f(false);
ASSERT_FALSE(e2);
ASSERT_THROW(*e2, bad_expected_access<error_code>);

auto e3 = g(true, 1, 2);
ASSERT_FALSE(e2);
Expand Down