1

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
  • 13
  • 116
  • 190
Thomas Klier
  • 449
  • 4
  • 16
  • 1
    Please define "generic type". Note `QVariant` is generic. Possible provide an example of use (attempt of use). For now IMO question suffers from [XY problem](https://mywiki.wooledge.org/XyProblem). – Marek R Aug 03 '23 at 11:22

1 Answers1

3

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.

463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185