From 9a12d44e82bb6c572891ca5227cdedad157f7638 Mon Sep 17 00:00:00 2001 From: Jarod42 Date: Sun, 3 Sep 2023 22:02:54 +0200 Subject: [PATCH] Improve `ranges::find` to support projection. --- src/include/util.h | 18 +++++++++++++++--- src/spell/script_spell.cpp | 3 +-- src/spell/spells.cpp | 2 +- src/ui/ui.cpp | 3 +-- 4 files changed, 18 insertions(+), 8 deletions(-) diff --git a/src/include/util.h b/src/include/util.h index 7719fec62..864761eee 100644 --- a/src/include/util.h +++ b/src/include/util.h @@ -165,6 +165,17 @@ fs::path GetExecutablePath(); /*---------------------------------------------------------------------------- -- Ranges ----------------------------------------------------------------------------*/ +#include + +struct identity +{ + template + T &&operator()(T &&arg) const + { + return std::forward(arg); + } +}; + namespace ranges { @@ -180,10 +191,11 @@ namespace ranges std::iota(begin(range), end(range), startValue); } - template - auto find(Range& range, const Value& value) + template + auto find(Range& range, const Value& value, Proj proj = {}) { - return std::find(begin(range), end(range), value); + return std::find_if( + begin(range), end(range), [&](const auto &elem) { return std::invoke(proj, elem) == value; }); } template diff --git a/src/spell/script_spell.cpp b/src/spell/script_spell.cpp index c3a59786a..a49f7ff3b 100644 --- a/src/spell/script_spell.cpp +++ b/src/spell/script_spell.cpp @@ -307,8 +307,7 @@ static int CclDefineSpell(lua_State *l) const int args = lua_gettop(l); std::string_view identname = LuaToString(l, 1); - const auto it = ranges::find_if(SpellTypeTable, - [&](const SpellType *spell) { return spell->Ident == identname; }); + const auto it = ranges::find(SpellTypeTable, identname, &SpellType::Ident); SpellType *spell = nullptr; if (it != SpellTypeTable.end()) { spell = *it; diff --git a/src/spell/spells.cpp b/src/spell/spells.cpp index 05d1a86c3..ddea289f0 100644 --- a/src/spell/spells.cpp +++ b/src/spell/spells.cpp @@ -416,7 +416,7 @@ void InitSpells() */ SpellType &SpellTypeByIdent(const std::string_view &ident) { - auto it = ranges::find_if(SpellTypeTable, [&](const SpellType* spell) { return spell->Ident == ident; }); + auto it = ranges::find(SpellTypeTable, ident, &SpellType::Ident); if (it != SpellTypeTable.end()) { return **it; } diff --git a/src/ui/ui.cpp b/src/ui/ui.cpp index 9b396a62a..c31db58b8 100644 --- a/src/ui/ui.cpp +++ b/src/ui/ui.cpp @@ -188,8 +188,7 @@ CUserInterface::CUserInterface() : */ CPopup &PopupByIdent(std::string_view ident) { - const auto it = - ranges::find_if(UI.ButtonPopups, [&](CPopup *popup) { return popup->Ident == ident; }); + const auto it = ranges::find(UI.ButtonPopups, ident, &CPopup::Ident); if (it != UI.ButtonPopups.end()) { return **it; }