Reputation: 1577
Lets say I parse a file and will get a string vector as a result which contains various data types. I'm now looking for a function like:
template<typename T>
T convertToType(const std::string& str);
which can do this conversion. Ideally I should be able to somehow provide my own conversion function, i.e. if T is an own complex type. Is there a way around having to pass it as a parameter everytime?
I was thinking about some sort of:
if(typeof(T) == double)
std::stod(str)
// ...
else
throw std::logical_error("Type not supported yet!");
Another option would be to write a template specialization for each type but this seems to make the use of a template function pretty useless if I have to specify it for each type again...
Upvotes: 1
Views: 56
Reputation: 70392
This is turning Joachim's comment into an answer.
Use std::istringstream
and let the input operator >>
handle it.
std::istringstream iss(str);
T result;
if (!(iss >> result)) {
throw std::logical_error("Type conversion failed!");
}
return result;
Upvotes: 1