如何将libconfig::Setting从一个libconfig::Config复制到另一个实例
问题描述
你有两个配置文件:
/home/work/father.config内容:
father_config = { child_config = "/home/work/child.config"; father_int = 1; };
/home/work/child.config内容:
child_config = { child_int =2; };
需求是在加载后的child_cfg对象中读取到father_int的值,要求实现灵活的复合配置段复制,不需要硬编码单个值的类型,支持直接复制libconfig::Setting::TypeGroup类型的整段配置。
你原有实现中直接给Group类型的Setting赋值不生效,已知的硬编码单值复制方案不符合灵活复制的需求。
解决方案
libconfig++ 提供了原生的深拷贝方法Setting::copy(),专门用于任意类型Setting节点的复制,包括Group、Array、List等复合类型,不需要硬编码子项的类型和键名,完全符合你的需求。
另外注意你原有代码中lookup的键名和实际配置文件中的键名不一致,需要调整成和配置匹配的名称才能正确读取节点。
正确实现代码
#include <iostream> #include <libconfig.h++> using namespace std; using namespace libconfig; int main() { // 加载父配置 Config father_cfg; father_cfg.readFile("/home/work/father.config"); const Setting& father_config = father_cfg.lookup("father_config"); // 读取子配置路径,加载子配置 const string& child_path = father_config.lookup("child_config"); Config child_cfg; child_cfg.readFile(child_path); Setting& child_root = child_cfg.getRoot(); // 核心复制逻辑 // 1. 在子配置根节点添加和源节点同类型的Group节点,键名自定义为father_config Setting& target_group = child_root.add("father_config", Setting::TypeGroup); // 2. 调用copy方法深拷贝整段Group的所有内容 target_group.copy(father_config); // 测试:从child_cfg中读取father_int的值 int father_int = child_cfg.lookup("father_config.father_int"); cout << father_int << endl; // 如果你希望把father_int放到child_config节点下,用下面的写法即可 // Setting& child_config = child_root.lookup("child_config"); // Setting& inner_group = child_config.add("father_config", Setting::TypeGroup); // inner_group.copy(father_config); // int father_int = child_cfg.lookup("child_config.father_config.father_int"); return 0; }
原代码不生效的原因
直接对Group类型的Setting使用=赋值仅能处理基础类型的值,不会递归复制Group下的所有子节点,必须用专门的copy()方法完成复合类型的深拷贝。
内容的提问来源于stack exchange,提问作者nick
相关产品推荐
相关产品推荐

