() returns true. As far as I know, only QVariant::toInt(bool *ok) can tell, if the value actually can " /> () returns true. As far as I know, only QVariant::toInt(bool *ok) can tell, if the value actually can " /> () returns true. As far as I know, only QVariant::toInt(bool *ok) can tell, if the value actually can "/>

Generic way to find out if a QVariant contains a valid number

69 views Asked by At

Inconveniently, QVariant{"Test"}.canconvert<int>() returns true.

As far as I know, only QVariant::toInt(bool *ok) can tell, if the value actually can be converted to an int. But I cannot use this function in a template class when I don't know the type.

Is there a way to check if the value actually can be converted to a generic type?

1

There are 1 answers

0
463035818_is_not_an_ai On

I am not eniterly sure what do you mean with "dont know the type". You need to know the type for cannconvert<int> just as you need to know the type for QVariant::toInt(bool *ok).

I am not into this Qt facilities and I assume you simply need a way to use QVariant::toInt(bool *ok) in generic code where you need QVariant::toT for other types T. Then you can do this:

// your code:
template <typename T>
void foo(QVariant& v) {
     // bool b;           // don't 
     // V.toInt(&b);      // do this

     my_canconvert<int>(v);    // but this
}

Where my_canconvert is a function template with respective specializations:

template <typename T> bool my_canconvert(const QVariant&);

// specializations...
template <> bool my_canconvert<int>(const QVariant&) {
       // use QVariant::toInt here...
}

template <> bool my_canconvert<double>(const QVariant&) { 
       // check if can convert to double
}

This is how you can provide your own generic customization of non-generic functions. However, as already mentioned, I am not into QVariant and I didnt bother to look it up. I suspect that there is a better way to use it. The above is more like a general approach in case nothing else helps.