oh_my_loam/common/config/yaml_config.h

56 lines
1.3 KiB
C
Raw Normal View History

2021-01-04 21:26:09 +08:00
#pragma once
#include <yaml-cpp/yaml.h>
2021-01-05 02:09:40 +08:00
2021-01-04 21:26:09 +08:00
#include <string>
#include "common/log/log.h"
#include "common/macro/macros.h"
namespace common {
class YAMLConfig {
public:
2021-01-22 16:33:55 +08:00
void Init(const std::string &file) {
2021-01-04 21:26:09 +08:00
config_.reset(new YAML::Node);
*config_ = YAML::LoadFile(file);
}
template <typename T>
2021-01-22 16:33:55 +08:00
const T Get(const std::string &key) const {
2021-01-04 21:26:09 +08:00
AFATAL_IF(!config_) << "Not initialized, please call Init first.";
return (*config_)[key].as<T>();
}
2021-01-22 16:33:55 +08:00
const YAML::Node &config() const {
2021-01-04 21:26:09 +08:00
AFATAL_IF(!config_) << "Not initialized, please call Init first.";
return *config_;
}
2021-01-29 20:45:09 +08:00
template <typename T>
static const std::vector<T> GetSeq(const YAML::Node &node) {
2021-02-02 21:06:45 +08:00
ACHECK(node.IsSequence());
2021-01-29 20:45:09 +08:00
std::vector<T> seq;
for (auto it = node.begin(); it != node.end(); ++it) {
seq.push_back(it->as<T>());
}
return seq;
}
template <typename TK, typename TV>
static const std::map<TK, TV> GetMap(const YAML::Node &node) {
2021-02-02 21:06:45 +08:00
ACHECK(node.IsMap());
2021-01-29 20:45:09 +08:00
std::map<TK, TV> map;
for (auto it = node.begin(); it != node.end(); ++it) {
map.insert({it->first.as<TK>(), it->second.as<TV>()});
}
return map;
}
2021-01-04 21:26:09 +08:00
private:
std::unique_ptr<YAML::Node> config_{nullptr};
2021-01-26 00:32:14 +08:00
2021-01-04 21:26:09 +08:00
DECLARE_SINGLETON(YAMLConfig);
};
} // namespace common