From ca3fef78f2e56af060b08eec0622fa0dea8dfb78 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1=C5=A1=20Kol=C3=A1rik?= Date: Fri, 13 Sep 2024 15:56:29 +0200 Subject: [PATCH] Added a view to just the names of `TermNames` --- src/common/TermNames.h | 28 ++++++++++++++++++++++++---- 1 file changed, 24 insertions(+), 4 deletions(-) diff --git a/src/common/TermNames.h b/src/common/TermNames.h index e071712ce..fd6fe3e89 100644 --- a/src/common/TermNames.h +++ b/src/common/TermNames.h @@ -7,6 +7,7 @@ #include #include +#include #include #include @@ -76,6 +77,8 @@ class TermNames { bool empty() const noexcept { return scopedNamesAndTerms.empty(); } std::size_t size() const noexcept { return scopedNamesAndTerms.size(); } + // A const view to just the names + inline auto names() const; // A const view to just the terms inline auto terms() const; @@ -86,7 +89,10 @@ class TermNames { using NameToTermMap = std::unordered_map; using TermToNamesMap = std::unordered_map, PTRefHash>; - class TermsView; + template + class NamesOrTermsView; + using NamesView = NamesOrTermsView; + using TermsView = NamesOrTermsView; // avoid undesired overload resolution with the public `namesForTerm` std::vector & _namesForTerm(PTRef term) const { @@ -118,17 +124,26 @@ class TermNames { TermToNamesMap termToNames; }; -class TermNames::TermsView { +template +class TermNames::NamesOrTermsView { public: - explicit TermsView(TermNames const & termNames_) : termNames{termNames_} {} + explicit NamesOrTermsView(TermNames const & termNames_) : termNames{termNames_} {} class Iterator { public: using PairIterator = ScopedNamesAndTerms::const_iterator; + using Value = std::conditional_t; + explicit Iterator(PairIterator pit) : pairIterator{pit} {} - PTRef operator*() const { return pairIterator->second; } + Value operator*() const { + if constexpr (namesView) { + return pairIterator->first; + } else { + return pairIterator->second; + } + } Iterator & operator++() { ++pairIterator; @@ -151,10 +166,15 @@ class TermNames::TermsView { bool empty() const noexcept { return termNames.scopedNamesAndTerms.empty(); } std::size_t size() const noexcept { return termNames.scopedNamesAndTerms.size(); } + protected: TermNames const & termNames; }; +auto TermNames::names() const { + return NamesView(*this); +} + auto TermNames::terms() const { return TermsView(*this); }