From 8b7d44fb4dbd2bdd5c46a0e0201fe44babd6bbfd Mon Sep 17 00:00:00 2001 From: Yedidya Feldblum Date: Sun, 2 Jul 2017 10:22:35 -0700 Subject: [PATCH] In-place construction for Try Summary: [Folly] In-place construction for `Try`. Using `in_place` as the first argumenbt. Avoid move operations. Reviewed By: Orvid Differential Revision: D5362568 fbshipit-source-id: 5c2aaf5dba1253c59e384940add411f0f2b570b2 --- folly/Try.h | 6 ++++++ folly/test/TryTest.cpp | 38 +++++++++++++++++++++++++++----------- 2 files changed, 33 insertions(+), 11 deletions(-) diff --git a/folly/Try.h b/folly/Try.h index f115a34a..df48794e 100644 --- a/folly/Try.h +++ b/folly/Try.h @@ -21,6 +21,7 @@ #include #include #include +#include #include #include #include @@ -81,6 +82,11 @@ class Try { */ explicit Try(T&& v) : contains_(Contains::VALUE), value_(std::move(v)) {} + template + explicit Try(in_place_t, Args&&... args) noexcept( + noexcept(::new (nullptr) T(std::declval()...))) + : contains_(Contains::VALUE), value_(std::forward(args)...) {} + /// Implicit conversion from Try to Try template /* implicit */ diff --git a/folly/test/TryTest.cpp b/folly/test/TryTest.cpp index 49517bf5..ae9e301f 100644 --- a/folly/test/TryTest.cpp +++ b/folly/test/TryTest.cpp @@ -19,22 +19,26 @@ #include #include +#include #include using namespace folly; -TEST(Try, basic) { - class A { - public: - A(int x) : x_(x) {} - - int x() const { - return x_; - } - private: - int x_; - }; +namespace { +class A { + public: + explicit A(int x) : x_(x) {} + + int x() const { + return x_; + } + private: + int x_; +}; +} + +TEST(Try, basic) { A a(5); Try t_a(std::move(a)); @@ -43,6 +47,18 @@ TEST(Try, basic) { EXPECT_EQ(5, t_a.value().x()); } +TEST(Try, in_place) { + Try t_a(in_place, 5); + + EXPECT_EQ(5, t_a.value().x()); +} + +TEST(Try, in_place_nested) { + Try> t_t_a(in_place, in_place, 5); + + EXPECT_EQ(5, t_t_a.value().value().x()); +} + // Make sure we can copy Trys for copyable types TEST(Try, copy) { Try t; -- 2.34.1