Search code examples
c++qtqstring

Convert QStrings to other types


I want to convert QStrings to different types. I would like to do this as generically and easy as possible without having to write an explicit method for each type.

I thought of using a template function, something like this:

template<typename T>
void getValueFromString(QString str, T& returnVal)
{
    returnVal = static_cast<T>(str);
}

Obviously this doesn't work, but something like that I would like to have.

Is there an easy way to do that?


Solution

  • You may use stream:

    template<typename T>
    void getValueFromString(QString str, T& returnVal)
    {
        QTextStream stream(str);
        stream >> returnVal;
    }