如何在c++中编写通用转换函数?



我需要使用已经编写的库读取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());
}

如果设置了文件结束标志,则预计读取另一个字符会失败,这确保了整个字符串已被读取-但是,如果末尾有空格可用,则会失败,因此您可能希望使该函数容忍。

如果你真的想走模板路线…

解决方案是将std::stod包装在一个lambda中,该lambda接受一组确定的参数。然后将该lambda赋值给与模板期望匹配的std::函数。我还更新了代码,以更一致地通过const引用传递项。

#include <string>
#include <functional>
#include <iostream>
template <typename T, typename R>
static bool convertFunction(const T& a, R& b, std::function<R (const 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;
std::function<double (const std::string&)> S2D = [](const std::string& s) -> double {
return std::stod(s);
};
convertFunction(x, y, S2D);
std::cout<<"value of y is "<<y<<std::endl;
return 0;
}

最新更新