参数

Posted by     "LETTER" on Wednesday, July 23, 2025

使用单例模式对yaml-cpp进行二次包装,实现全局的参数管理

config.h

#pragma once

#ifndef __CONFIG_H__
#define __CONFIG_H__

#include <yaml-cpp/yaml.h>
#include <memory>
#include <fstream>

class Config {
private:
    static std::shared_ptr<Config> config_;
    YAML::Node param_file_;

    Config() {}  // private constructor makes a singleton
public:
    ~Config();  // close the file when deconstructing

    static bool SetParameterFile(const std::string &filename);

    // access the parameter values
    static YAML::Node GetParam(const std::string &key) {
        return Config::config_->slam_file_[key];
    }

    template <typename T>
    static T GetParam(const std::string &father_key, const std::string &child_key) {
        try {
            return Config::config_->slam_file_[father_key][child_key].as<T>();
        } catch (...) {
            std::cout << "Error: " << father_key << " " << child_key << " parameter does not exist." << std::endl;
            return T();
        }
    }

    template <typename T>
    static T GetParam(const std::string &father_key, const std::string &child_key, T intial) {
        T value = intial;
        if (Config::config_->slam_file_[father_key][child_key]) {
            value = Config::config_->slam_file_[father_key][child_key].as<T>();
        } else {
            std::cout << "Warning: " << father_key << " " << child_key << " parameter does not exist, use default value " << value << std::endl;
        }
        return value;
    }
};

#endif  // __CONFIG_H__

config.cpp

#include "config.h"

bool Config::SetParameterFile(const std::string &filename)
{
    if (config_ == nullptr)
        config_ = std::shared_ptr<Config>(new Config);

    std::ifstream param_file(filename);
    if (!param_file) {
        std::cout<< "Error: " << filename << " does not exist." << std::endl;
        return false;
    }
    config_->param_file_ = YAML::LoadFile(filename);
    if (config_->param_file_.IsNull())
    {
        std::cout<< "Error: " << filename << " is not a valid YAML file." << std::endl;
        return false;
    }
    return true;
}

Config::~Config()
{}

std::shared_ptr<Config> Config::config_ = nullptr;