I need to convert a string that represents a vector of T
s into the corresponding vector.
My problem is that I'd like to pass a simple argument: the converter function. Here's the split
:
template <class T>
auto split(const std::string &s, const std::function<T(const std::string&)> &convert, char sep = ',') -> std::vector<T>
{
std::stringstream ss(s);
std::vector<T> result;
while (ss.good())
{
std::string substr;
std::getline(ss, substr, sep);
if (!substr.empty())
result.push_back(convert(substr));
}
return result;
};
It fails to compile when passing standard functions such as std::stoi
because of the default parameters of std::stoi
:
auto q = split<int>(subs, std::stoi);
error: no matching function for call to 'split'
auto q = split<int>(subs, std::stoi);
^~~~~~~~~~
And obviously I can trick the compiler by using a lambda function:
auto q = split<std::size_t>(subs, [](const std::string &s){ return std::stoul(s); });
Is there a metaprogramming trick that allows me to somehow ignore the default parameters?
Aucun commentaire:
Enregistrer un commentaire