Debian Codegraph @

src/atlas/util/Registry.h

raw
1 /*
2 * (C) Copyright 2021 ECMWF.
3 *
4 * This software is licensed under the terms of the Apache Licence Version 2.0
5 * which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
6 * In applying this licence, ECMWF does not waive the privileges and immunities
7 * granted to it by virtue of its status as an intergovernmental organisation
8 * nor does it submit to any jurisdiction.
9 */
10
11 #pragma once
12
13 #include <map>
14 #include <ostream>
15 #include <string>
16 #include <utility>
17 #include <vector>
18
19 #include "atlas/runtime/Exception.h"
20 #include "atlas/runtime/Log.h"
21
22 namespace atlas {
23 namespace util {
24
25 template <typename T>
26 class Registry {
27 public:
28 Registry() = default;
29
30 void add(const std::string& key, T&& value) {
31 ATLAS_ASSERT_MSG(m_.emplace(key, std::move(value)).second, "ObjectRegistry: duplicate '" + key + "'");
32 }
33
34 bool has(const std::string& key) { return m_.find(key) != m_.end(); }
35
36 T get(const std::string& key) {
37 auto j = m_.find(key);
38 if (j != m_.end()) {
39 return j->second;
40 }
41
42 list(Log::error() << "Registry: unknown '" << key << "', choices are: ");
43 throw_Exception("Registry: unknown '" + key + "'");
44 }
45
46 void list(std::ostream& out) {
47 const char* sep = "";
48 for (const auto& j : m_) {
49 out << sep << j.first;
50 sep = ", ";
51 }
52 }
53
54 std::vector<std::string> keys() {
55 std::vector<std::string> keys;
56 for (const auto& j : m_) {
57 keys.push_back(j.first);
58 }
59 return keys;
60 }
61
62 private:
63 std::map<std::string, T> m_;
64 };
65
66 } // namespace util
67 } // namespace atlas