I have a function that I'd like to generalize. Simply put, I have a std::string s that I process with a parser generating a std::vector<std::string> (it's a list as in "1, 2, 3"), and the function should return a std::vector<T>, with T restricted to double or int.
The vector should contain the transformed values.
I am stuck with the last parameter of std::transform, as it should switch between std::stod and std::stoi. The solution I am looking for is with template metaprogramming magic, not with if (std::is_same<T,int>::value).
Any hints?
template <class T>
auto get_vector(std::string s) -> std::vector<T>
{
std::vector<T> v;
auto tmp = split(s);
std::transform(tmp.begin(), tmp.end(), std::back_inserter(v), ??);
return v;
}
Dispatching to std::stoi and std::stod via function template specialization:
template <typename T>
auto parse_number(std::string const& s) -> T;
template <>
auto parse_number<int>(std::string const& s) -> int
{
return std::stoi(s);
}
template <>
auto parse_number<double>(std::string const& s) -> double
{
return std::stod(s);
}
template <class T>
auto get_vector(std::string const& s) -> std::vector<T>
{
std::vector<T> v;
auto tmp = split(s);
std::transform(tmp.begin(), tmp.end(), std::back_inserter(v), &parse_number<T>);
return v;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With