C++解析配置文件初体验

  |   0 评论   |   0 浏览

背景

找一个C++解析配置文件的类。

初体验

代码

代码:https://github.com/marzer/tomlplusplus

示例

配置文件示例

[library]
name = "toml++"
authors = ["Mark Gillard <[email protected]>"]

[dependencies]
cpp = 17

解析

#include <toml++/toml.hpp>

auto config = toml::parse_file( "configuration.toml" );

// get key-value pairs
std::string_view library_name = config["library"]["name"].value_or(""sv);
std::string_view library_author = config["library"]["authors"][0].value_or(""sv);
int64_t depends_on_cpp_version = config["dependencies"]["cpp"].value_or(0);

// modify the data
config.insert_or_assign("alternatives", toml::array{
    "cpptoml",
    "toml11",
    "Boost.TOML"
});

// use a visitor to iterate over heterogenous data
config.for_each([](auto& key, auto& value)
{
    std::cout << value << "\n";
    if constexpr (toml::is_string<decltype(value)>)
        do_something_with_string_values(value);
});

// you can also iterate more 'traditionally' using a ranged-for
for (auto&& [k, v] : config)
{
    // ...
}

// re-serialize as TOML
std::cout << config << "\n";

// re-serialize as JSON
std::cout << toml::json_formatter{ config } << "\n";

// re-serialize as YAML
std::cout << toml::yaml_formatter{ config } << "\n";

C++11初体验

上面那个实现是C++17的,这里用一个C++11的实现。

代码

https://github.com/ToruNiina/toml11

示例

#include <toml.hpp>
#include <iostream>

int main()
{
    // ```toml
    // title = "an example toml file"
    // nums  = [3, 1, 4, 1, 5]
    // ```
    auto data = toml::parse("example.toml");

    // find a value with the specified type from a table
    std::string title = toml::find<std::string>(data, "title");

    // convert the whole array into any container automatically
    std::vector<int> nums = toml::find<std::vector<int>>(data, "nums");

    // access with STL-like manner
    if(!data.contains("foo"))
    {
        data["foo"] = "bar";
    }

    // pass a fallback
    std::string name = toml::find_or<std::string>(data, "name", "not found");

    // width-dependent formatting
    std::cout << std::setw(80) << data << std::endl;

    return 0;
}

参考

  1. TOML
  2. TOML 11 for Modern C++