Skip to content

Commit

Permalink
Add folly::Optional::to_optional for easier std::optional conversion
Browse files Browse the repository at this point in the history
Summary: see title. `static_cast<optional<T>>(foo)` is too much typing. I like thrift optional_field_ref<T>'s to_optional (though on a side note I thought operator* of optional_field_ref T would give me a std::optional but i was wrong)

Reviewed By: yfeldblum

Differential Revision: D57116214

fbshipit-source-id: 970f4de50ae2fe8e057b320d6c2c881e55aefac7
  • Loading branch information
Yi Zhang authored and facebook-github-bot committed May 15, 2024
1 parent 8f2d73f commit 993de7e
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 1 deletion.
10 changes: 9 additions & 1 deletion third-party/folly/src/folly/Optional.h
Original file line number Diff line number Diff line change
Expand Up @@ -201,7 +201,7 @@ class Optional {
construct(*newValue);
}
}
/// Allow implict cast to std::optional
/// Allow explicit cast to std::optional
/// @methodset Migration
explicit operator std::optional<Value>() && noexcept(
std::is_nothrow_move_constructible<Value>::value) {
Expand All @@ -217,6 +217,14 @@ class Optional {
: std::nullopt;
}

std::optional<Value> toStdOptional() && noexcept {
return static_cast<std::optional<Value>>(std::move(*this));
}

std::optional<Value> toStdOptional() const& noexcept {
return static_cast<std::optional<Value>>(*this);
}

/// Set the Optional
/// @methodset Modifiers
void assign(const None&) { reset(); }
Expand Down
11 changes: 11 additions & 0 deletions third-party/folly/src/folly/test/OptionalTest.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -840,11 +840,17 @@ TEST(Optional, StdOptionalConversions) {
folly::Optional<int> f = 42;
std::optional<int> s = static_cast<std::optional<int>>(f);
EXPECT_EQ(*s, 42);
EXPECT_EQ(s, f.toStdOptional());
EXPECT_TRUE(f);

f = static_cast<folly::Optional<int>>(s);
EXPECT_EQ(*f, 42);
EXPECT_TRUE(s);

folly::Optional<int> e;
EXPECT_FALSE(static_cast<std::optional<int>>(e));
EXPECT_FALSE(e.toStdOptional());

const folly::Optional<int> fc = 12;
s = static_cast<std::optional<int>>(fc);
EXPECT_EQ(*s, 12);
Expand All @@ -856,6 +862,11 @@ TEST(Optional, StdOptionalConversions) {
fp = static_cast<folly::Optional<std::unique_ptr<int>>>(std::move(sp));
EXPECT_EQ(**fp, 42);
EXPECT_FALSE(sp);

folly::Optional<std::unique_ptr<int>> fp2 = std::make_unique<int>(42);
auto sp2 = std::move(fp2).toStdOptional();
EXPECT_EQ(**sp2, 42);
EXPECT_FALSE(fp2);
}

TEST(Optional, MovedFromOptionalIsEmpty) {
Expand Down

0 comments on commit 993de7e

Please sign in to comment.