简体   繁体   中英

How do I set constant configuration parameters at run-time

I am trying to achieve the following. I want to store some of the system information in a set of variables.

Say the variables are:

std::string GPU;
std::string CPU;
std::string OS;

I want these variables to have global scope, but only for reading (they should not be modified). Normally for this one would simply append const to the declaration. However for some of these variables I need to find the information at runtime after main has executed.

The issues is thus that I cannot simply initialize them statically as one normally would, I need to wait until some processing has been made to set them.

Overall I need the variables to be initialized once and exactly once by a function and then just be readable.

Is this achievable at all?

Why not hide required constants behind private static scope of a struct? In multithreaded environment you may even add a conditional variable and wait for initialization.

struct globals {
    static const std::string& GPU() {assert(is_inited_); return gpu_;}
    static init(std::string GPU, ...) {gpu_ = std::move(GPU); ...; is_inited_ = true;}
  private:
    std::string gpu_;
    std::string cpu_;
    std::string os_;
    book is_inited_;
};

int main() {
  ...
  // initialize consts at some point
  globals::init();
  ...
  // access consts
  globals::GPU();
}

// initial values
std::string globals::gpu_;
...
bool globals::is_inited_ = false;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM