[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.
This commit is contained in:
Benjamin Kramer 2022-12-04 17:30:33 +01:00
parent 856f7937c7
commit 02c75e8465
2 changed files with 31 additions and 2 deletions

View File

@ -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 @@ public:
}
};
// 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

View File

@ -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 {