[llvm] [ADT] Allow structured binding on StringMap of move-only type (PR #110043)

via llvm-commits llvm-commits at lists.llvm.org
Wed Sep 25 14:25:12 PDT 2024


llvmbot wrote:


<!--LLVM PR SUMMARY COMMENT-->

@llvm/pr-subscribers-llvm-adt

Author: Ryan Blue (rzblue)

<details>
<summary>Changes</summary>

Currently, `decltype(auto)` evaluates to `ValueTy` rather than `ValueTy&`. Parenthesizing the return value fixes this, but a non-const overload needed to be added to allow use of structured binding on a non-const `StringMapEntry`.

---
Full diff: https://github.com/llvm/llvm-project/pull/110043.diff


2 Files Affected:

- (modified) llvm/include/llvm/ADT/StringMapEntry.h (+12-2) 
- (modified) llvm/unittests/ADT/StringMapTest.cpp (+10) 


``````````diff
diff --git a/llvm/include/llvm/ADT/StringMapEntry.h b/llvm/include/llvm/ADT/StringMapEntry.h
index 98b51cc1aebd59..2dac30d05ee092 100644
--- a/llvm/include/llvm/ADT/StringMapEntry.h
+++ b/llvm/include/llvm/ADT/StringMapEntry.h
@@ -148,14 +148,24 @@ class StringMapEntry final : public StringMapEntryStorage<ValueTy> {
   }
 };
 
-// Allow structured bindings on StringMapEntry.
+// Allow structured bindings on const StringMapEntry.
 template <std::size_t Index, typename ValueTy>
 decltype(auto) get(const StringMapEntry<ValueTy> &E) {
   static_assert(Index < 2);
   if constexpr (Index == 0)
     return E.first();
   else
-    return E.second;
+    return (E.second);
+}
+
+// Allow structured bindings on StringMapEntry.
+template <std::size_t Index, typename ValueTy>
+decltype(auto) get(StringMapEntry<ValueTy> &E) {
+  static_assert(Index < 2);
+  if constexpr (Index == 0)
+    return E.first();
+  else
+    return (E.second);
 }
 
 } // end namespace llvm
diff --git a/llvm/unittests/ADT/StringMapTest.cpp b/llvm/unittests/ADT/StringMapTest.cpp
index c9ef3f8a096ee9..b35afc6cec40ed 100644
--- a/llvm/unittests/ADT/StringMapTest.cpp
+++ b/llvm/unittests/ADT/StringMapTest.cpp
@@ -552,6 +552,16 @@ TEST_F(StringMapTest, StructuredBindings) {
   }
 }
 
+TEST_F(StringMapTest, StructuredBindingsMoveOnly) {
+  StringMap<MoveOnly> A;
+  A.insert(std::make_pair("a", MoveOnly(42)));
+
+  for (auto &&[Key, Value] : A) {
+    EXPECT_EQ("a", Key);
+    EXPECT_EQ(42, Value.i);
+  }
+}
+
 namespace {
 // Simple class that counts how many moves and copy happens when growing a map
 struct CountCtorCopyAndMove {

``````````

</details>


https://github.com/llvm/llvm-project/pull/110043


More information about the llvm-commits mailing list