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

Ryan Blue via llvm-commits llvm-commits at lists.llvm.org
Wed Sep 25 14:24:10 PDT 2024


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

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`.

>From b050443ad661baa1862e2cd7217f02d692529981 Mon Sep 17 00:00:00 2001
From: Ryan Blue <ryanzblue at gmail.com>
Date: Wed, 25 Sep 2024 17:01:53 -0400
Subject: [PATCH] StringMap: fix structured bindings with move-only types

---
 llvm/include/llvm/ADT/StringMapEntry.h | 14 ++++++++++++--
 llvm/unittests/ADT/StringMapTest.cpp   | 10 ++++++++++
 2 files changed, 22 insertions(+), 2 deletions(-)

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 {



More information about the llvm-commits mailing list