How to convert QString to typename using templates?

I would like to write a generic template method that calculates some things and returns a value at the end typename T. The value is obtained from QString, so I need to convert the QString to the specified one typename T. Unfortunately, I find only the methods toDouble(), toInt()....

What I need:

QString s = 3.1415;
double d = s.toType<double>();
float f = s.toType<float>();
int i = s.toType<int>();

I do not want to call toDouble(), toInt()... because I cannot select them at compile time.

Thanks!


Edit: I could write my own specialized template functions that do just that. So,

double myOwnConvertFunction<double>(const QString& s)

then just call s.toDouble ()

I thought Qt might already have a built-in way?

+5
3

QString QVariant value<T>()

QVariant(s).value<T>()

QVariant QString, , . Qt

qvariant_cast<T>(s)
+7

QTextStream. , QTextStream QString. , , :

template <typename T>
T toType(const QString& string) {
    T result;
    QTextStream stream(&string, QIODevice::ReadOnly);

    stream >> result;
    return result;
}

, , pre-gcc 5.0 stringstream -, QTextStream inline :

template <typename T>
T toType(const QString& string) {
    T result;

    QTextStream(&string, QIODevice::ReadOnly) >> result;
    return result;
}   
+2

- toType:

template <typename T> struct type { };

template <typename T>
auto toType(QString const& q)
    -> decltype(toType(q, type<T>{}))
{
    return toType(q, type<T>{});
}

:

double toType(QString const& q, type<double> ) {
    return q.toDouble();
}

int toType(QString const& q, type<int> ) {
    return q.toInt();
}

float toType(QString const& q, type<float> ) {
    return q.toFloat();
}

...
+1

Source: https://habr.com/ru/post/1614281/


All Articles