c++ - 如何用 C++ 编写通用转换函数?

标签 c++ templates c++14

我需要使用已编写的库读取 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/

相关文章:

c++ - C++中复制构造函数的困惑

c++ - eclipse-cdt boost\shared_ptr.hpp : no such file in directory, 但它是包含文件的一部分

c++ - 返回静态变量的成员函数

c++ - 从包装器接口(interface)动态转换

c++ - 如何将模板参数包扩展为一系列模板化参数?

c++ - 如何在编译时生成嵌套循环

c# - 将引用类型从 C++ 编码到 C#

c++ - 在 C++ 中如何像 Java 那样定义列表列表或堆栈列表?

c++ - 派生类的模板特化

c++ - RVO 是否适用于对象成员?