toml++ 用于 C++:完整指南与示例

面向初学者的在线Python训练器

轻松学习Python,无需理论负担。在浏览器中直接解决带自动检查的实践任务,无需安装任何东西。

开始课程

toml++ 用于 C++:完整指南与示例

\n\n

1. 什么是 toml++ 以及它的用途

\n\n

TOML(Tom's Obvious Minimal Language)是一种配置文件格式,作为 INI、YAML 和 JSON 的替代方案而创建。它的设计目标是对人类具有最大可读性,能够明确映射到哈希表,并且易于解析。与 YAML 不同,TOML 不允许歧义(例如缩进或数据类型方面),而与 JSON 不同,它不需要为键加引号,并且支持注释。

\n\n

toml++(也称为 tomlplusplus)是一个现代的、仅头文件(header-only)的库,用于在 C++17 及以上版本中解析和生成 TOML 文件。它无需编译:您只需包含头文件即可获得完整功能。这使其成为重视集成简便性、性能和严格类型化的项目的理想选择。

\n\n

为什么要使用 toml++?首先,它提供了对 TOML v1.0 规范的完整支持,包括内联表、表数组、日期、时间和本地日期。其次,它注重类型安全:您得到的不是原始的 JSON 类似对象,而是严格类型化的值(std::string、int64_t、double、bool、toml::date 等)。第三,它速度极快,且依赖项最少(仅需 C++17 标准库)。

\n\n

2. 安装

\n\n

toml++ 是一个仅头文件的库。这意味着您无需单独编译它。只需将头文件复制到您的项目中并包含它们即可。

\n\n

方法 1:Vcpkg(推荐用于 Windows 和 Linux)

\n
# 通过 vcpkg 安装\nvcpkg install tomlplusplus\n\n# 在 CMakeLists.txt 中连接\nfind_package(tomlplusplus CONFIG REQUIRED)\ntarget_link_libraries(my_project PRIVATE tomlplusplus::tomlplusplus)\n
\n\n

方法 2:Conan

\n
# 通过 Conan 安装\nconan install tomlplusplus/3.4.0@\n\n# 在 conanfile.txt 中\n[requires]\ntomlplusplus/3.4.0\n\n[generators]\nCMakeDeps\n
\n\n

方法 3:手动安装(最简单)

\n
# 从 GitHub 下载最新版本\nwget https://github.com/marzer/tomlplusplus/archive/refs/tags/v3.4.0.tar.gz\ntar -xzf v3.4.0.tar.gz\n\n# 将 include/toml++ 文件夹复制到您的项目中\ncp -r tomlplusplus-3.4.0/include/toml++ /path/to/your/project/include/\n\n# 在您的代码中直接包含:\n#include <toml++/toml.h>\n
\n\n

方法 4:CMake FetchContent(适用于 CMake 项目)

\n
include(FetchContent)\nFetchContent_Declare(\n    tomlplusplus\n    GIT_REPOSITORY https://github.com/marzer/tomlplusplus.git\n    GIT_TAG v3.4.0\n)\nFetchContent_MakeAvailable(tomlplusplus)\n\ntarget_link_libraries(my_project PRIVATE tomlplusplus::tomlplusplus)\n
\n\n

3. 快速入门 — 最小工作示例

\n\n

创建文件 config.toml:

\n
# config.toml\ntitle = "配置示例"\n\n[server]\nhost = "localhost"\nport = 8080\ndebug = true\n\n[database]\nname = "mydb"\nuser = "admin"\npassword = "secret123"\n
\n\n

现在编写 C++ 代码来读取它:

\n
#include <toml++/toml.h>\n#include <iostream>\n#include <filesystem>\n\nint main() {\n    // 1. 解析文件\n    auto config = toml::parse_file("config.toml");\n\n    // 2. 读取简单值\n    std::string title = config["title"].value_or("default");\n    std::cout << "标题: " << title << std::endl;\n\n    // 3. 读取嵌套表\n    auto server = config["server"];\n    std::string host = server["host"].value_or("localhost");\n    int port = server["port"].value_or(3000);\n                    

推荐