I have a C++
function that takes a comma separated string and splits in a std::vector<std::string>
:
std::vector<std::string> split(const std::string& s, const std::string& delim, const bool keep_empty = true) {
std::vector<std::string> result;
if (delim.empty()) {
result.push_back(s);
return result;
}
std::string::const_iterator substart = s.begin(), subend;
while (true) {
subend = std::search(substart, s.end(), delim.begin(), delim.end());
std::string temp(substart, subend);
if (keep_empty || !temp.empty()) {
result.push_back(temp);
}
if (subend == s.end()) {
break;
}
substart = subend + delim.size();
}
return result;
}
However, I would really like to be able to apply this function to mutiple datatypes. For instance, if I have the input std::string
:
1,2,3,4,5,6
then I'd like the output of the function to be a vector of int
s. I'm fairly new to C++
, but I know there are something called template
types, right? Would this be possible to create this function as a generic template? Or am I misunderstanding how template
functions work?