Add folly::Identity function object to Utility.h; replace AtomicHashArray's AHAIdenti...
[folly.git] / folly / Utility.h
index f8f4f9bb07d5e5a94156f04f46f43637ed4b7098..4d6725d7070ec70e9684d19db915100c6fc5e9cc 100644 (file)
@@ -131,4 +131,31 @@ template <std::size_t N>
 using make_index_sequence = detail::make_index_sequence<N>;
 
 #endif
+
+/**
+ * A simple function object that passes its argument through unchanged.
+ *
+ * Example:
+ *
+ *   int i = 42;
+ *   int &j = Identity()(i);
+ *   assert(&i == &j);
+ *
+ * Warning: passing a prvalue through Identity turns it into an xvalue,
+ * which can effect whether lifetime extension occurs or not. For instance:
+ *
+ *   auto&& x = std::make_unique<int>(42);
+ *   cout << *x ; // OK, x refers to a valid unique_ptr.
+ *
+ *   auto&& y = Identity()(std::make_unique<int>(42));
+ *   cout << *y ; // ERROR: y did not lifetime-extend the unique_ptr. It
+ *                // is no longer valid
+ */
+struct Identity {
+  using is_transparent = void;
+  template <class T>
+  constexpr T&& operator()(T&& x) const noexcept {
+    return static_cast<T&&>(x);
+  }
+};
 }