From: Eric Niebler Date: Sun, 8 Jan 2017 05:44:02 +0000 (-0800) Subject: add folly::as_const, like C++17's std::as_const X-Git-Tag: v2017.03.06.00~119 X-Git-Url: http://demsky.eecs.uci.edu/git/?a=commitdiff_plain;h=3cec19d4760d9b4057c7e4a6464be86aad216a73;p=folly.git add folly::as_const, like C++17's std::as_const Summary: A one-liner from C++17, but a useful one. Const-qualifies an lvalue reference, avoiding the need for an awkward const_cast in some cases. Reviewed By: yfeldblum Differential Revision: D4389929 fbshipit-source-id: 1650c4901489eb0dd62fd9fa633b4a0da9f01954 --- diff --git a/folly/Utility.h b/folly/Utility.h index a7692505..385ed34a 100644 --- a/folly/Utility.h +++ b/folly/Utility.h @@ -68,4 +68,32 @@ constexpr typename std::decay::type copy(T&& value) noexcept( noexcept(typename std::decay::type(std::forward(value)))) { return std::forward(value); } + +/** + * A simple helper for getting a constant reference to an object. + * + * Example: + * + * std::vector v{1,2,3}; + * // The following two lines are equivalent: + * auto a = const_cast&>(v).begin(); + * auto b = folly::as_const(v).begin(); + * + * Like C++17's std::as_const. See http://wg21.link/p0007 + */ +#if __cpp_lib_as_const || _MSC_VER + +/* using override */ using std::as_const + +#else + +template +constexpr T const& as_const(T& t) noexcept { + return t; +} + +template +void as_const(T const&&) = delete; + +#endif } diff --git a/folly/test/UtilityTest.cpp b/folly/test/UtilityTest.cpp index 337ade5a..df8fa5d2 100644 --- a/folly/test/UtilityTest.cpp +++ b/folly/test/UtilityTest.cpp @@ -59,3 +59,19 @@ TEST_F(UtilityTest, copy_noexcept_spec) { EXPECT_FALSE(noexcept(folly::copy(thr))); EXPECT_TRUE(noexcept(folly::copy(std::move(thr)))); // note: does not copy } + +TEST_F(UtilityTest, as_const) { + struct S { + bool member() { + return false; + } + bool member() const { + return true; + } + }; + S s; + EXPECT_FALSE(s.member()); + EXPECT_TRUE(folly::as_const(s).member()); + EXPECT_EQ(&s, &folly::as_const(s)); + EXPECT_TRUE(noexcept(folly::as_const(s))); +}