Commit 8c89c7dd authored by Mike Curtiss's avatar Mike Curtiss Committed by Jordan DeLong

folly::make_optional

Summary:
Helper method for creating a folly::Optional<T> by just passing
in a T reference.  Analogous to boost::make_optional.

Test Plan: Added test case

Reviewed By: tjackson@fb.com

FB internal diff: D721762
parent cb610acb
......@@ -268,6 +268,12 @@ void swap(Optional<T>& a, Optional<T>& b) {
}
}
}// namespace folly
template<class T,
class Opt = Optional<typename std::decay<T>::type>>
Opt make_optional(T&& v) {
return Opt(std::forward<T>(v));
}
} // namespace folly
#endif//FOLLY_OPTIONAL_H_
/*
* Copyright 2012 Facebook, Inc.
* Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
......@@ -274,3 +274,38 @@ TEST(Optional, Pointee) {
x = none;
EXPECT_FALSE(get_pointer(x));
}
TEST(Optional, MakeOptional) {
// const L-value version
const std::string s("abc");
auto optStr = make_optional(s);
ASSERT_TRUE(optStr.hasValue());
EXPECT_EQ(*optStr, "abc");
*optStr = "cde";
EXPECT_EQ(s, "abc");
EXPECT_EQ(*optStr, "cde");
// L-value version
std::string s2("abc");
auto optStr2 = make_optional(s2);
ASSERT_TRUE(optStr2.hasValue());
EXPECT_EQ(*optStr2, "abc");
*optStr2 = "cde";
// it's vital to check that s2 wasn't clobbered
EXPECT_EQ(s2, "abc");
// L-value reference version
std::string& s3(s2);
auto optStr3 = make_optional(s3);
ASSERT_TRUE(optStr3.hasValue());
EXPECT_EQ(*optStr3, "abc");
*optStr3 = "cde";
EXPECT_EQ(s3, "abc");
// R-value ref version
unique_ptr<int> pInt(new int(3));
auto optIntPtr = make_optional(std::move(pInt));
EXPECT_TRUE(pInt.get() == nullptr);
ASSERT_TRUE(optIntPtr.hasValue());
EXPECT_EQ(**optIntPtr, 3);
}
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment