summaryrefslogtreecommitdiff
path: root/src/cfgparser.h
blob: 321432d5cbe3eae7ffab5436e61b119e20fe729b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
/*
 * \brief TFE配置文件读取封装
 *
 * 因MESA_Prof_load为C编写的库,采用了返回值的风格报告运行错误,比较麻烦。在这里,将MESA_Prof_Load封装为
 * C++接口,将返回值错误报告方法改为异常,便于调用者集中处理异常。
 *
 * \author Lu Qiuwen<[email protected]>
 * \date 2018-5-25
 */

#pragma once
#include <stdexcept>
#include <string>
#include <cstring>

extern "C"
{
#include <MESA_prof_load.h>
}

#include "util.h"

class TfeConfigParser
{
public:
    TfeConfigParser(std::string cfgfile) : str_cfgfile_(std::move(cfgfile))
    {}
    ~TfeConfigParser() = default;

    /* 读入函数 */
    template<typename T>
    T GetValue(const std::string &str_section, const std::string &str_entry);

    template<typename T>
    T GetValueWithDefault(const std::string &str_section, const std::string &str_entry, const T & default_value);

    template<typename T>
    std::pair<bool, T> TryGetValue(const std::string & str_section, const std::string & str_entry);

    const std::string & Source() { return str_cfgfile_; }

private:
    static constexpr unsigned TFE_STRING_MAX = 2048;
    std::string str_cfgfile_;
};

template<typename T>
T TfeConfigParser::GetValueWithDefault(const std::string &str_section, const std::string &str_entry, const T & default_value)
{
    T __value;

    try
    {
        __value = GetValue<T>(str_section, str_entry);
    }
    catch (...)
    {
        return default_value;
    }

    return __value;
}

template<typename T>
std::pair<bool, T> TfeConfigParser::TryGetValue(const std::string & str_section, const std::string & str_entry)
{
    T __value;
    try
    {
        __value = GetValue<T>(str_section, str_entry);
    }
    catch (...)
    {
        return {false, {}};
    }

    return {true, __value};
}