我需要将表示向量01s的字符串转换为相应的向量。将默认值作为忽略它们的参数传递
我的问题是,我想通过一个简单的参数:转换器功能。这里的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;
};
它无法通过标准功能时,如因std::stoi
的std::stoi
默认参数为它的签名是int stoi(const string& __str, size_t* __idx = 0, int __base = 10);
编译:
auto q = split<int>(subs, std::stoi);
error: no matching function for call to 'split'
auto q = split<int>(subs, std::stoi);
^~~~~~~~~~
很显然我可以欺骗编译器使用lambda函数:
auto q = split<std::size_t>(subs, [](const std::string &s){ return std::stoul(s); });
是否有一个元编程技巧,允许我索姆ehow 忽略的默认参数?
默认参数是什么意思?你明确指定你想要'分割'。 –
nwp
我的意思是'std :: stoi'实际上有默认参数:签名是'int stoi(常量字符串&__str,size_t * __idx = 0,int __base = 10);'。我希望忽略该默认签名。 – senseiwa
如果你可以避免使用std :: function,它会让你的生活更轻松。 (模板化的函数参数会更好。) – alfC