hyperrealm / libconfig

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

why libconfig::Setting is private? #159

Closed nickhuangxinyu closed 4 years ago

nickhuangxinyu commented 4 years ago

How should i do if i want to use libconfig::setting as function parameter?

thomastrapp commented 4 years ago

How should i do if i want to use libconfig::setting as function parameter?

This works, for example:

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

void example(const libconfig::Setting& settings)
{
  std::string abc = settings.lookup("abc");
  std::cout << abc << "\n";
}

int main()
{
  libconfig::Config config;
  config.readString("abc = \"abc\";");

  example(config.getRoot());

  return 0;
}
nickhuangxinyu commented 4 years ago

How should i do if i want to use libconfig::setting as function parameter?

This works, for example:

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

void example(const libconfig::Setting& settings)
{
  std::string abc = settings.lookup("abc");
  std::cout << abc << "\n";
}

int main()
{
  libconfig::Config config;
  config.readString("abc = \"abc\";");

  example(config.getRoot());

  return 0;
}

Can I save setting in a class as a member variable, waiting to use it in the future? like: Class A { A(libconfig::Setting s) : a(s) {

} private: libconfig::Setting a; }

int main() { libconfig::Config config; config.readString("abc = \"abc\";"); A(config.lookup("abc")); }

I dont think this works

Can you offer some suggestions, i am bothered by this for a long time

thomastrapp commented 4 years ago

A(libconfig::Setting s) : a(s)

Unfortunately, that doesn't work, because libconfig::Setting can not be copied (by design).

Can you offer some suggestions

It depends on your use case. Personally, I think a good approach is to never pass a libconfig::Setting when possible, but the setting's value instead. It makes for clearer code.

class Connection
{
public:
  Connection(std::string hostname, int port);
}
// ...
std::string hostname = config.lookup("hostname");
int port = config.lookup("port");
Connection connection(hostname, port);
nickhuangxinyu commented 4 years ago

@thomastrapp thx a lot!