Commit 3cec19d4 authored by Eric Niebler's avatar Eric Niebler Committed by Facebook Github Bot

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
parent 3cdd3857
...@@ -68,4 +68,32 @@ constexpr typename std::decay<T>::type copy(T&& value) noexcept( ...@@ -68,4 +68,32 @@ constexpr typename std::decay<T>::type copy(T&& value) noexcept(
noexcept(typename std::decay<T>::type(std::forward<T>(value)))) { noexcept(typename std::decay<T>::type(std::forward<T>(value)))) {
return std::forward<T>(value); return std::forward<T>(value);
} }
/**
* A simple helper for getting a constant reference to an object.
*
* Example:
*
* std::vector<int> v{1,2,3};
* // The following two lines are equivalent:
* auto a = const_cast<const std::vector<int>&>(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 <class T>
constexpr T const& as_const(T& t) noexcept {
return t;
}
template <class T>
void as_const(T const&&) = delete;
#endif
} }
...@@ -59,3 +59,19 @@ TEST_F(UtilityTest, copy_noexcept_spec) { ...@@ -59,3 +59,19 @@ TEST_F(UtilityTest, copy_noexcept_spec) {
EXPECT_FALSE(noexcept(folly::copy(thr))); EXPECT_FALSE(noexcept(folly::copy(thr)));
EXPECT_TRUE(noexcept(folly::copy(std::move(thr)))); // note: does not copy 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)));
}
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