Phyth v0.1.0
A dimensional safe C++ header-only mechanics and electromagnetics simulation library.
Loading...
Searching...
No Matches
UnitsRegistry.hpp
Go to the documentation of this file.
1#ifndef PHYTH_UNIT_REGISTRY_HPP
2#define PHYTH_UNIT_REGISTRY_HPP
3
4#include <string>
5#include <unordered_map>
6#include <typeindex>
7#include <mutex>
8
9namespace Phyth {
15 struct UnitInfo {
16 std::string name;
17 std::string symbol;
18 };
19
41 public:
49 return registry;
50 }
51
61 template<typename UnitT>
62 void RegisterUnit(const std::string &name, const std::string &symbol) {
63 std::lock_guard lock(mutex_);
64 registry_[std::type_index(typeid(UnitT))] = {.name = name, .symbol = symbol};
65 }
66
75 template<typename UnitT>
76 std::string GetName() const {
77 if (const auto it = registry_.find(std::type_index(typeid(UnitT))); it != registry_.end()) {
78 return it->second.name;
79 }
80 return "";
81 }
82
91 template<typename UnitT>
92 std::string GetSymbol() const {
93 if (const auto it = registry_.find(std::type_index(typeid(UnitT))); it != registry_.end()) {
94 return it->second.symbol;
95 }
96 return "";
97 }
98
99 private:
100 UnitRegistry() = default;
101
102 std::unordered_map<std::type_index, UnitInfo> registry_;
103 mutable std::mutex mutex_; // mutable to allow locking in const methods
104 };
105
121 template<typename UnitT>
129 UnitRegistrar(const std::string &name, const std::string &symbol) {
131 }
132 };
133}
134
135#endif // PHYTH_UNIT_REGISTRY_HPP
Singleton registry for unit names and symbols.
std::unordered_map< std::type_index, UnitInfo > registry_
std::string GetName() const
Get the full name of a unit type.
static UnitRegistry & GetInstance()
Get the singleton instance.
std::string GetSymbol() const
Get the symbol of a unit type.
UnitRegistry()=default
void RegisterUnit(const std::string &name, const std::string &symbol)
Register a unit type with its display information.
std::string symbol
constexpr bool is_unit_v
Definition Unit.hpp:79
Display information for a unit type.
Static registrar for unit types.
UnitRegistrar(const std::string &name, const std::string &symbol)
Register the unit with the given name and symbol.