简体   繁体   中英

C++ template function to split string to array

I read a text file which contains lines each line contains data separated by delimiters like spaces or commas , I have a function which split a string to array but I want to make it a template to get different types like floats or integers beside string, I made two functions one for split to strings and the the other to floats

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);
    }
}

the template function works fine with strings, in the other function I use atof(item.c_str()) to get the float value from string, when I use the template function with floats I get invalid cast from type 'const char*' to type 'float'

so how could I make the casting in the template function?

You cannot do:

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

In your case, you could declare a template, eg from_string<T> , and replace the line with:

T f = from_string<T>(item);

The you would implement it with something like:

// 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...

You could use the strtof function ( http://en.cppreference.com/w/cpp/string/byte/strtof )

so something like this

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM