littlebot
Published on 2025-04-08 / 8 Visits
0

【源码】基于C++的TOML数据处理库

项目简介

本项目是一个基于C++的TOML数据处理库,用于解析和生成TOML格式的数据。TOML是简单易读的数据序列化格式,常用于配置文件。该库为C++开发者提供便捷方式处理TOML数据,具备良好性能与兼容性。

项目的主要特性和功能

  • 头文件可选:支持单头文件版本,使用灵活。
  • TOML标准支持:支持最新的TOML v1.0.0版本,还能选择支持部分未发布的TOML特性。
  • 测试覆盖全面:通过toml - test套件的所有测试。
  • 多格式序列化:支持将TOML数据序列化为JSON和YAML格式。
  • UTF - 8处理:对UTF - 8编码数据正确处理,包括BOM。
  • 低依赖:不依赖RTTI,可在有或没有异常的环境中工作。
  • 跨平台与编译器兼容:在Clang(8 +)、GCC(8 +)和MSVC(VS2019)上测试,支持x64、x86和ARM架构。

安装使用步骤

假设你已下载本项目的源码文件,以下是不同方式的安装和使用步骤:

单头文件版本

  1. toml.hpp 文件放置到你的源代码目录中。
  2. 无需其他额外步骤。

常规版本

  1. 复制项目仓库。
  2. tomlplusplus/include 添加到你的包含路径中。
  3. 在代码中使用 #include <toml++/toml.hpp> 引入库。

其他包管理器

  • Conan:在 conanfile 中添加 tomlplusplus/3.4.0
  • DDS:在 package.json5 中添加 tomlpp^3.4.0
  • Tipi.build:在 .tipi/deps 中添加 "marzer/tomlplusplus": {}
  • Vcpkg:执行 vcpkg install tomlplusplus
  • Meson:执行 meson wrap install tomlplusplus,之后可作为常规依赖使用。
  • CMake FetchContent:在CMake文件中添加以下代码: cmake include(FetchContent) FetchContent_Declare( tomlplusplus GIT_TAG v3.4.0 ) FetchContent_MakeAvailable(tomlplusplus)

基本使用示例

假设存在一个 configuration.toml 文件: ```toml [library] name = "toml++" authors = ["Mark Gillard mark.gillard@outlook.com.au"]

[dependencies] cpp = 17 使用C++代码读取该文件:cpp

include

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

// 获取键值对 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);

// 修改数据 config.insert_or_assign("alternatives", toml::array{ "cpptoml", "toml11", "Boost.TOML" });

// 遍历数据 config.for_each( { std::cout << value << "\n"; if constexpr (toml::is_string) do_something_with_string_values(value); });

// 重新序列化为TOML、JSON、YAML std::cout << config << "\n"; std::cout << toml::json_formatter{ config } << "\n"; std::cout << toml::yaml_formatter{ config } << "\n"; ```

下载地址

点击下载 【提取码: 4003】【解压密码: www.makuang.net】