The reason for the error is that your template will be specilized at compilation as (example given for int
):
template<>
vector<int> string_to_token(string &str, const char* delim, TO_TYPE to_type)
{
// ...
switch(to_type)
{
case TO_INT:
{
vector<int> res;
// ...
return res; // this is OK
}
break;
case TO_FLOAT:
{
vector<float> res;
// ...
return res; // this will attempt to return vector<float> for a vector<int>
}
break;
case TO_STRING:
{
vector<string> res;
// ...
return res; // this will attempt to return vector<string> for a vector<int>
}
break;
}
}
You are essentially trying to solve two problems with this function:
tokenization (see solutions here)
string conversion.
Consider splitting this function in two parts:
first, a non-templated function that tokenizes the string into a std::vector.
second, a transformation (that can be easily templated by type):
Code:
std::vector<std::string> strings = tokenize(str, ","); // see link above
std::vector<int> ints{strings.size()};
std::transform(strings.begin(), strings.end(), ints.begin(),
[](const std::string& s) { return std::stoi(s); });