Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vector of doubles/ints template function

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;
}
like image 529
senseiwa Avatar asked Feb 03 '17 16:02

senseiwa


1 Answers

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;
}
like image 58
yuri kilochek Avatar answered Sep 30 '22 05:09

yuri kilochek