[llvm] 02c75e8 - [ADT] Enable structured bindings for iterating StringMap

Benjamin Kramer via llvm-commits llvm-commits at lists.llvm.org
Sun Dec 4 09:36:32 PST 2022


Author: Benjamin Kramer
Date: 2022-12-04T18:33:16+01:00
New Revision: 02c75e8465c8a637a0b32e8330458f4cb516a283

URL: https://github.com/llvm/llvm-project/commit/02c75e8465c8a637a0b32e8330458f4cb516a283
DIFF: https://github.com/llvm/llvm-project/commit/02c75e8465c8a637a0b32e8330458f4cb516a283.diff

LOG: [ADT] Enable structured bindings for iterating StringMap

const references only for now, we can add overloads to have a mutable or
movable `second` if the need arises.

Added: 
    

Modified: 
    llvm/include/llvm/ADT/StringMapEntry.h
    llvm/unittests/ADT/StringMapTest.cpp

Removed: 
    


################################################################################
diff  --git a/llvm/include/llvm/ADT/StringMapEntry.h b/llvm/include/llvm/ADT/StringMapEntry.h
index 27d82916503e..b5fc6d595f86 100644
--- a/llvm/include/llvm/ADT/StringMapEntry.h
+++ b/llvm/include/llvm/ADT/StringMapEntry.h
@@ -16,9 +16,8 @@
 #ifndef LLVM_ADT_STRINGMAPENTRY_H
 #define LLVM_ADT_STRINGMAPENTRY_H
 
-#include "llvm/ADT/None.h"
-#include "llvm/ADT/STLFunctionalExtras.h"
 #include "llvm/ADT/StringRef.h"
+#include <optional>
 
 namespace llvm {
 
@@ -149,6 +148,26 @@ class StringMapEntry final : public StringMapEntryStorage<ValueTy> {
   }
 };
 
+// Allow structured bindings on 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;
+}
+
 } // end namespace llvm
 
+namespace std {
+template <typename ValueTy>
+struct tuple_size<llvm::StringMapEntry<ValueTy>>
+    : std::integral_constant<std::size_t, 2> {};
+
+template <std::size_t I, typename ValueTy>
+struct tuple_element<I, llvm::StringMapEntry<ValueTy>>
+    : std::conditional<I == 0, llvm::StringRef, ValueTy> {};
+} // namespace std
+
 #endif // LLVM_ADT_STRINGMAPENTRY_H

diff  --git a/llvm/unittests/ADT/StringMapTest.cpp b/llvm/unittests/ADT/StringMapTest.cpp
index e5dae25c4408..415d7f6c31f5 100644
--- a/llvm/unittests/ADT/StringMapTest.cpp
+++ b/llvm/unittests/ADT/StringMapTest.cpp
@@ -517,6 +517,16 @@ TEST_F(StringMapTest, MoveDtor) {
   ASSERT_TRUE(B.empty());
 }
 
+TEST_F(StringMapTest, StructuredBindings) {
+  StringMap<int> A;
+  A["a"] = 42;
+
+  for (auto &[Key, Value] : A) {
+    EXPECT_EQ("a", Key);
+    EXPECT_EQ(42, Value);
+  }
+}
+
 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