mardi 2 août 2016

How do I load custom "const" variables from a config file in C++?

I currently have a function which loads variables from a config file. It uses these to initialise a set of constant config variables.

// header file
namespace cfg {
    extern const char *config_value;
}

// source file 
namespace cfg {
    const char *config_value;
}

bool load_config() {
    cfg::config_value = load_config_line("config_value");
}

const char *load_config_line(const char *key) {
       // read value from config.cfg...
}

This works pretty well. The problem is that now I want to reuse this code in several other projects, which means the constant values have to change. This means changing the config_value names in four different places each in the code. It also means I have several copies of essentially the same code to maintain in different projects.

Is there a way of setting different sets of constant values using the same code for the reading and parsing? Perhaps so that all I have to do is change the header file and it automatically finds those value names in the config file? The tricky part is that ideally the outward facing config values themselves should be constant and available at compile time (using a string to value map for example is undesirable, as I would prefer to have the compile time protection).

Aucun commentaire:

Enregistrer un commentaire