hyperrealm / libconfig

C/C++ library for processing configuration files
https://hyperrealm.github.io/libconfig/
GNU Lesser General Public License v2.1
1.13k stars 366 forks source link

copy libconfig::Setting from one libconfig::Config to another? #202

Closed nickhuangxinyu closed 3 years ago

nickhuangxinyu commented 3 years ago

I have a config ("/home/work/father.config") looks like:

father_config = {
  child_config = "/home/work/child.config";
  father_int = 1;
};

in /home/work/child.config:

child_config = {
  child_int =2;
};

what i want is to get father_intfrom child_cfg, please see the code:

 #include <iostream>
  #include <libconfig.h++>

  using namespace std;

  int main() {
    libconfig::Config father_cfg;
    father_cfg.readFile("./father.cfg");
    const libconfig::Setting& father_setting = father_cfg.lookup("father_setting");
    const std::string& child_path = father_setting.lookup("child_path");
    libconfig::Config child_cfg;
    child_cfg.readFile(child_path);
    libconfig::Setting& child_setting = child_cfg.lookup("child_setting");
    auto & s = child_cfg.getRoot().add("father_int", libconfig::Setting::TypeGroup);// father_setting.lookup("father_int");
    s = father_setting;  // !!!!!!! this doesn't work
    int father_int = child_setting.lookup("father_int");  // the ulimate purpose is to make father int can be found in child_cfg
    cout << father_int;
  }

I know if the father_int is type int and the key-father_int wont change, i can use:

int father_int = father_setting.lookup("father_int");
child_cfg.GetRoot().add("father_int", libconfig::Setting::TypeInt) = father_int;

but i want this can be more flexible, which need to add libconfig::Setting::TypeGroup instead of libconfig::Setting::TypeInt,

Can you help on this?

hyperrealm commented 3 years ago

There isn't an API provided to add an existing Setting to another, because this would allow all kinds of misuse like adding a setting to itself, adding a parent of a setting as its child, and so on, which would cause problems when it came time to deallocate the setting tree.

What you probably want is:

father_config = { @include "/home/work/child.config" father_int = 1; };