From 2263ab2ae7af4ee06265d28778a2d065c549e7a9 Mon Sep 17 00:00:00 2001 From: feixyz10 Date: Fri, 16 Oct 2020 00:22:03 +0800 Subject: [PATCH] add config singleton --- common/config.h | 36 ++++++++++++++++++++++++++++++++++++ common/micros.h | 22 ++++++++++++++++++++++ 2 files changed, 58 insertions(+) create mode 100644 common/config.h create mode 100644 common/micros.h diff --git a/common/config.h b/common/config.h new file mode 100644 index 0000000..8157dd5 --- /dev/null +++ b/common/config.h @@ -0,0 +1,36 @@ +#pragma once + +#include + +#include + +#include "log.h" +#include "micros.h" + +namespace oh_my_slam { + +class Config { + public: + void SetConfigFile(const std::string& file) { + config_.reset(new YAML::Node); + *config_ = YAML::LoadFile(file); + } + + template + const T& Get(const std::string& key) const { + AFATAL_IF(!config_) << "No config exists: please call SetConfigFile."; + return (*config_)[key].as(); + } + + const YAML::Node& config() const { + AFATAL_IF(!config_) << "No config exists: please call SetConfigFile."; + return *config_; + } + + private: + std::shared_ptr config_{nullptr}; + + DECLARE_SINGLETON(Config); +}; + +} // namespace oh_my_slam \ No newline at end of file diff --git a/common/micros.h b/common/micros.h new file mode 100644 index 0000000..d3de164 --- /dev/null +++ b/common/micros.h @@ -0,0 +1,22 @@ +#pragma once + +#include +#include + +// adapted form baidu apollo cyber/common/macros.h, it is thread safe +#define DECLARE_SINGLETON(classname) \ + public: \ + static classname* Instance() { \ + static std::unique_ptr instance = nullptr; \ + if (!instance) { \ + static std::once_flag flag; \ + std::call_once(flag, \ + [&] { instance.reset(new (std::nothrow) classname()); }); \ + } \ + return instance.get(); \ + } \ + \ + private: \ + classname() = default; \ + classname(const classname&) = delete; \ + classname& operator=(const classname&) = delete; \ No newline at end of file