[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:
parent
856f7937c7
commit
02c75e8465
|
@ -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
|
||||
|
|
|
@ -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 {
|
||||
|
|
Loading…
Reference in New Issue