【问题标题】:C++ template function to split string to arrayC ++模板函数将字符串拆分为数组
【发布时间】:2017-12-07 22:31:39
【问题描述】:

我读取了一个包含行的文本文件,每行包含由空格或逗号等分隔符分隔的数据,我有一个将字符串拆分为数组的函数,但我想将其作为模板来获取不同类型,例如浮点数或整数字符串,我做了两个函数,一个用于拆分为字符串,另一个用于浮动

template<class T>
void split(const std::string &s, char delim, std::vector<T>& result) {
    std::stringstream ss(s);
    std::string item;
    while (std::getline(ss, item, delim)) {
        T f = static_cast<T>(item.c_str());
        result.push_back(f);
    }
}

void fSplit(const std::string &s, char delim, std::vector<GLfloat>& result) {
    std::stringstream ss(s);
    std::string item;
    while (std::getline(ss, item, delim)) {
        GLfloat f = atof(item.c_str());
        result.push_back(f);
    }
}

模板函数适用于字符串,在另一个函数中我使用atof(item.c_str())从字符串中获取浮点值,当我使用带有浮点数的模板函数时,我得到invalid cast from type 'const char*' to type 'float'

那么我怎样才能在模板函数中进行强制转换呢?

【问题讨论】:

  • 您不能在完全不相关的类型之间进行转换,例如将字符串转换为数值。我建议你对specialization做一些研究,然后实现专门的功能。
  • 好的,我会的,谢谢
  • @Someprogrammerdude 那么我可以检查类的类型然后选择正确的方法来获得价值吗?我试过typeid,但我得到错误我认为它与编译器变量cannot use typeid with -fno-rtti有关

标签: c++ templates casting


【解决方案1】:

你不能这样做:

T f = static_cast<T>(item.c_str());

在您的情况下,您可以声明一个模板,例如from_string&lt;T&gt;,并将该行替换为:

T f = from_string<T>(item);

你可以用类似的东西来实现它:

// Header
template<typename T>
T from_string(const std::string &str);

// Implementations
template<>
int from_string(const std::string &str)
{
    return std::stoi(str);
}

template<>
double from_string(const std::string &str)
{
    return std::stod(str);
}

// Add implementations for all the types that you want to support...

【讨论】:

    【解决方案2】:

    你可以使用 strtof 函数 (http://en.cppreference.com/w/cpp/string/byte/strtof)

    像这样的

    GLfloat f = std::strtof (item.c_str(), nullptr);
    

    【讨论】:

    • 这不是问题,问题是在一个模板函数中使用它
    猜你喜欢
    • 2012-01-09
    • 2012-06-27
    • 1970-01-01
    • 2017-09-19
    • 1970-01-01
    • 1970-01-01
    • 2016-04-01
    • 2022-01-18
    • 1970-01-01
    相关资源
    最近更新 更多