I’m trying to read in an xml file where the xml attributes will denote the type of the data stored in the element like so:
<ElementName type="string">some_string</ElementName>
The not all types have to be supported, but I do need to support at least string, int, unsigned int, and float. It would be nice if it were extensible to other types.
I looked at using std::any and std::variant. I think std::any is closer to my use case because I am essentially storing the values in std::map<std::string, std::any> where the string would be ElementName for this case and the std::any would contain “some_string” and a type of std::string. These values will just be extracted from the map for use elsewhere as concrete types of std::string, int, unsigned int, etc.
I need to do something similar to this to access the data, but I don’t know what to do about the part marked “???”. I think it needs to have a specific return type, but I cant simply make it T and templatize it because the type of the value is being stored in the map and that knowledge is not known at the level where getValue is being called.
??? getValue (const std::string& key)
{
std::any val = my_map[key];
if (val.type() == typeid(int))
return std::any_cast<int>(val);
else if (val.type() == typeid(std::string))
return std::any_cast<std::string>(val);
else if (val.type() == typeid(float))
return std::any_cast<float>(val);
}
My feeling is there is some way to templatize this efficiently, but I’m just not seeing it right now.
Any help?