在C++项目开发中,经常需要将STL容器的数据转换为YAML格式进行存储或传输,yaml-cpp库提供的YAML::convert模板是实现这一功能的核心工具,通过自定义特化该模板可以完成各类STL容器的映射与序列化。

YAML::convert模板基础
YAML::convert是yaml-cpp库中用于定义自定义类型与YAML节点转换规则的模板类,默认情况下yaml-cpp已经为部分基础类型提供了转换支持,但STL容器需要开发者手动特化该模板来实现转换逻辑。
该模板主要包含两个静态方法:
- encode:将C++类型转换为YAML::Node,用于序列化操作
- decode:将YAML::Node转换为C++类型,用于反序列化操作
vector容器的序列化实现
以std::vector<int>为例,我们需要特化YAML::convert模板,实现向量到YAML序列的转换,以及YAML序列到向量的转换。
完整代码示例
#include <iostream>
#include <vector>
#include <yaml-cpp/yaml.h>
// 特化YAML::convert模板,处理std::vector<int>类型
namespace YAML {
template<>
struct convert<std::vector<int>> {
// 序列化:将vector转换为YAML节点
static Node encode(const std::vector<int>& vec) {
Node node(NodeType::Sequence);
for (int val : vec) {
node.push_back(val);
}
return node;
}
// 反序列化:将YAML节点转换为vector
static bool decode(const Node& node, std::vector<int>& vec) {
if (!node.IsSequence()) {
return false;
}
vec.clear();
for (const auto& item : node) {
vec.push_back(item.as<int>());
}
return true;
}
};
}
int main() {
// 测试序列化
std::vector<int> srcVec = {1, 2, 3, 4, 5};
YAML::Node node;
node["test_vector"] = srcVec;
std::cout << "序列化结果:" << std::endl;
std::cout << node << std::endl;
// 测试反序列化
std::vector<int> destVec;
if (node["test_vector"].as<std::vector<int>>(destVec)) {
std::cout << "反序列化结果:" << std::endl;
for (int val : destVec) {
std::cout << val << " ";
}
std::cout << std::endl;
}
return 0;
}
进阶用法:嵌套vector的序列化
如果是嵌套的vector类型,比如std::vector<std::vector<int>>,同样可以通过特化YAML::convert实现,yaml-cpp会自动递归调用对应类型的convert逻辑。
namespace YAML {
template<>
struct convert<std::vector<std::vector<int>>> {
static Node encode(const std::vector<std::vector<int>>& vec) {
Node node(NodeType::Sequence);
for (const auto& innerVec : vec) {
node.push_back(innerVec); // 自动调用std::vector<int>的convert逻辑
}
return node;
}
static bool decode(const Node& node, std::vector<std::vector<int>>& vec) {
if (!node.IsSequence()) {
return false;
}
vec.clear();
for (const auto& item : node) {
vec.push_back(item.as<std::vector<int>>());
}
return true;
}
};
}
注意事项
- 特化YAML::convert模板时需要放在YAML命名空间下,否则编译器无法识别
- encode方法需要保证返回的Node类型与实际数据结构匹配,序列容器对应NodeType::Sequence
- decode方法需要先校验Node的类型,避免转换失败导致程序异常
- 如果需要处理其他STL容器如map、list,只需要按照相同模式特化对应类型的convert模板即可
C++YAMLSTL_containervector序列化修改时间:2026-07-22 12:45:25