From: Yedidya Feldblum Date: Sun, 2 Jul 2017 17:22:33 +0000 (-0700) Subject: In-place construction for Optional X-Git-Tag: v2017.07.03.00~2 X-Git-Url: http://demsky.eecs.uci.edu/git/?a=commitdiff_plain;h=a695397e013de4596d05ca7fc1df2546ad639e64;p=folly.git In-place construction for Optional Summary: [Folly] In-place construction for `Optional`. Using `in_place` as the first argument. Avoid move operations. Reviewed By: Orvid, ot Differential Revision: D5362563 fbshipit-source-id: 771db2556842d5dec35d1bf2ad6c23358a417d54 --- diff --git a/folly/Optional.h b/folly/Optional.h index 16cf86a1..c6980c18 100644 --- a/folly/Optional.h +++ b/folly/Optional.h @@ -61,6 +61,7 @@ #include #include +#include namespace folly { @@ -126,6 +127,12 @@ class Optional { construct(newValue); } + template + explicit Optional(in_place_t, Args&&... args) + noexcept(noexcept(::new (nullptr) Value(std::declval()...))) { + construct(std::forward(args)...); + } + void assign(const None&) { clear(); } diff --git a/folly/test/OptionalTest.cpp b/folly/test/OptionalTest.cpp index ed84f753..d075eeab 100644 --- a/folly/test/OptionalTest.cpp +++ b/folly/test/OptionalTest.cpp @@ -195,6 +195,21 @@ TEST(Optional, EmptyConstruct) { EXPECT_FALSE(bool(test2)); } +TEST(Optional, InPlaceConstruct) { + using A = std::pair; + Optional opt(in_place, 5, 3.2); + EXPECT_TRUE(bool(opt)); + EXPECT_EQ(5, opt->first); +} + +TEST(Optional, InPlaceNestedConstruct) { + using A = std::pair; + Optional> opt(in_place, in_place, 5, 3.2); + EXPECT_TRUE(bool(opt)); + EXPECT_TRUE(bool(*opt)); + EXPECT_EQ(5, (*opt)->first); +} + TEST(Optional, Unique) { Optional> opt;