I have the following class:
class A {
public:
A()
: set_value(myvar1_, "myvar1", 0)
, set_value(myvar2_, "myvar2", 1.5)
{ }
int myvar1_;
double myvar2_;
std::string asString() const {
std::stringstream str;
str << "myvar1 = " << myvar1_
<< ", myvar2 = " << myvar2_;
return str.str();
}
private:
// other things exist here, unrelated to myvar1/2
};
Where set_value is a function that reads the values of the variables from some config file, and if not found uses the default value (the last argument). I also have myvar1_ and myvar2_ as public member variables, because they get accessed directly, and I'd like to keep that feature and do not want to add a potential function hop.
Now, you can see that I have typed myvar1 or myvar1_ in quite a few different places, and I'd like to make this more robust, so that I can type, somewhere somehow, myvar1_, "myvar1", 0 once, and automagically get the above functions called and values filled. I have a lot of variables and they get added or removed fairly frequently, and sometimes I forget to initialize them, or mistype the string name in set_value, or forget to add a new variable to asString.
Is that possible to do? I'd appreciate any hints.
Aucun commentaire:
Enregistrer un commentaire