add config singleton

main
feixyz10 2020-10-16 00:22:03 +08:00 committed by feixyz
parent a229e4b75d
commit 2263ab2ae7
2 changed files with 58 additions and 0 deletions

36
common/config.h Normal file
View File

@ -0,0 +1,36 @@
#pragma once
#include <yaml-cpp/yaml.h>
#include <string>
#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 <typename T>
const T& Get(const std::string& key) const {
AFATAL_IF(!config_) << "No config exists: please call SetConfigFile.";
return (*config_)[key].as<T>();
}
const YAML::Node& config() const {
AFATAL_IF(!config_) << "No config exists: please call SetConfigFile.";
return *config_;
}
private:
std::shared_ptr<YAML::Node> config_{nullptr};
DECLARE_SINGLETON(Config);
};
} // namespace oh_my_slam

22
common/micros.h Normal file
View File

@ -0,0 +1,22 @@
#pragma once
#include <memory>
#include <mutex>
// adapted form baidu apollo cyber/common/macros.h, it is thread safe
#define DECLARE_SINGLETON(classname) \
public: \
static classname* Instance() { \
static std::unique_ptr<classname> 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;