Skip to content

Instantly share code, notes, and snippets.

@notlesh
Last active March 17, 2020 20:15
Show Gist options
  • Save notlesh/f268f5872df54bdce1552ea412199480 to your computer and use it in GitHub Desktop.
Save notlesh/f268f5872df54bdce1552ea412199480 to your computer and use it in GitHub Desktop.
Using visitors instead of for-each
diff --git a/llarp/config/definition.cpp b/llarp/config/definition.cpp
index 5e45dee6..f6f8800a 100644
--- a/llarp/config/definition.cpp
+++ b/llarp/config/definition.cpp
@@ -60,17 +60,27 @@ Configuration::lookupDefinitionOrThrow(string_view section, string_view name)
const_cast<const Configuration*>(this)->lookupDefinitionOrThrow(section, name));
}
+using SectionVisitor = std::function<void(const std::string&, const DefinitionMap&)>;
+const auto visitSections = [](const SectionMap& sections, SectionVisitor visitor) {
+ for (const auto& pair : sections)
+ {
+ visitor(pair.first, pair.second);
+ }
+};
+
+using DefVisitor = std::function<void(const std::string&, const ConfigDefinition_ptr&)>;
+const auto visitDefinitions = [](const DefinitionMap& defs, DefVisitor visitor) {
+ for (const auto& pair : defs)
+ {
+ visitor(pair.first, pair.second);
+ }
+};
+
void
Configuration::validate()
{
- for (const auto& pair : m_definitions)
- {
- const std::string& section = pair.first;
-
- const auto& sectionDefinitions = pair.second;
- for (const auto& defPair : sectionDefinitions)
- {
- const auto& def = defPair.second;
+ visitSections(m_definitions, [&](const std::string& section, const DefinitionMap& defs) {
+ visitDefinitions(defs, [&](const std::string&, const ConfigDefinition_ptr& def) {
if (def->required and def->numFound < 1)
{
throw std::invalid_argument(stringify(
@@ -79,8 +89,8 @@ Configuration::validate()
// should be handled earlier in ConfigDefinition::parseValue()
assert(def->numFound == 1 or def->multiValued);
- }
- }
+ });
+ });
}
std::string
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment