2

I am trying to make a generic stringToVector function.

The input is a string that contains multiple int or string separated by comma (let's ignore char)

ex) [1, 5, 7] or [conver, to, string, vector]

I want a generic function like this

template <class T>
vector<T> stringToVector(string input) {
    vector<T> output;
    input = input.substr(1, input.length() - 2);

    stringstream ss;
    ss.str(input);
    T item;
    char delim = ',';
    while (getline(ss, item, delim)) {
        if (is_same(T, int)) {
            output.push_back(stoi(item));    // error if T is string
        } else {
            output.push_back(item);          // error if T is int
        }
    }

    return output;
}

Is there any way around?

I know this function is dumb, but I just want this for a competitive programming.

Sean
  • 489
  • 1
  • 8
  • 29

1 Answers1

3

Usually it is done by a helper function:

template<class T>
T my_convert( std::string data );

template<>
std::string my_convert( std::string data )
{
    return data;
}

template<>
int my_convert( std::string data )
{
    return std::stoi( data );
}

inside your function:

str::string str;
while (getline(ss, str, delim))
   output.push_back( my_convert<T>( std::move( str ) ) );

it will fail to compile for any other type than std::string or int but you can add more specializations of my_convert if you need to support other types.

Slava
  • 43,454
  • 1
  • 47
  • 90
  • You forgot to include the template parameters in front of your specializations. e.g. `template <> std::string my_convert(std::string data)`, `template <> int my_convert(std::string data)` – J. Willus Apr 23 '19 at 15:36
  • @J.Willus actually this is a good point, but gcc 8.3.0 hapily compiles it without explicit definition – Slava Apr 23 '19 at 17:40