我需要使用已编写的库读取 csv 文件,该库始终以字符串形式返回列值,因此作为验证和进一步处理的一部分,我需要将该字符串值转换为适当的类型(可以是 double、int、enum、bool) 、日期等),这是我写的,但这给出了错误,即 stod/stoi 等有多个重载。还有没有更好的方法来完成此任务。
bool convertFunction(T a, R& b,std::function<R (T)> fx)
{
bool isConverted = true;
try
{
b = fx(a);
}
catch(const std::exception& e)
{
isConverted = false;
}
return isConverted;
}
int main() {
std::string x = "2.54";
double y = 0.0;
bool isValid = convertFunction(x,y,std::stod);
std::cout<<"value of y is "<<y<<std::endl;
return 0;
}
最佳答案
完全通用的方法可能如下所示:
template <typename T>
bool convert(std::string const& text, T& value)
{
std::istringstream s(text);
s >> value;
char c;
return s && (s >> c, s.eof());
}
读取另一个字符预计会失败,并设置文件结束标志,这确保了整个字符串已被读取 - 但是,如果尾随空格可用,则失败,因此您可能还想将功能耐受。
关于c++ - 如何用 C++ 编写通用转换函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72358516/