I want to a program to read strings like:
integer_value 1
double_value 1.0
string_value one
I implement the following functions in order to read these:
void read_val_int(
std::vector<std::string> str_vec,
std::string str,
int& val){
if(str_vec[0]==str) val= std::stoi(str_vec[1]);
}
void read_val_dbl(
std::vector<std::string> str_vec,
std::string str,
double& val){
if(str_vec[0]==str) val= std::stoi(str_vec[1]);
}
void read_val_str(
std::vector<std::string> str_vec,
std::string str,
std::string& val){
if(str_vec[0]==str) val= str_vec[1];
}
str_vec
is a vector containing two string values, e.g. {"integer_value","1"}.
str
contains a string I want to compare with str_vec[0]
val
is an integer, double or string that corresponds to str_vec[1]
in case str_vec[0]==str
is true.
I use these functions as, e.g. read_val_int(my_str_vec,"integer_value",my_int_val)
.
My question is: Is there a way of using one single function in order to do this? I have tried using a template but since I need to reference val
this seems impossible.
Note: I'm aware of this post but it is in C and seems kinda messy to me. Maybe there is a simpler way to achieve this in C++.