2

Does this statis cast make sense FOR THIS EXPLICIT CASE?

QSqlQuery q;
enum MyEnumType;
obj.setMyEnumType(static_cast<MyEnumType>(q.value(2).toInt()));

or is a static cast for situations where the source type is not sure int?

the set function is

 void setMyEnumType(MyEnumTypetype type) { m_type = type; }

what is the advantage to a simple cast?

obj.setMyEnumType((MyEnumType)q.value(2).toInt());
wutzebaer
  • 14,365
  • 19
  • 99
  • 170

3 Answers3

3

Yes the cast makes perfect sense. Let's unpick this a little more:

QSqlQuery q;
enum MyEnumType;
const auto v1 = q.value(2);  // I don't know what the type of v1 will be.
                             // See the QSqlQuery docs.
const auto v2 = v1.toInt();  // v2 is going to be an int or a long or something.

obj.setMyEnumType(v2);       // Error: setMyEnumType doesn't take an int argument.

const auto e = static_cast<MyEnumType>(v2);
obj.setMyEnumType(e);        // OK.  Argument is now the right type.

Edit: Ah-ha! I see now you were asking an entirely different question. The question you were really asking is a duplicate of What is the difference between static_cast<> and C style casting?

Always prefer static_cast because a) a code reviewer will be prompted to think "what happens if the value is out of range?"; b) a code reviewer won't have to think "is this a static_cast, a reinterpret cast, a const cast, or some combination of all three - and is it safe?"

Community
  • 1
  • 1
1

It makes perfect sense to convert from int to an enum and back. You might check for boundary conditions (e.g., int is larger than last element of enum). Note that you're not casting the function here, but the return value.

lorro
  • 10,687
  • 23
  • 36
1

Your question is a bit of an XY problem in this scenario, as QVariant provides built-in conversion safety checks and casting.

Use qvariant_cast or QVariant::value<>(), alongside canConvert(), e.g.:

QVariant v = q.value(2);
if (v.canConvert<MyEnumType>()) {
    obj.setEnumType( qvariant_cast<MyEnumType>(v));
    ...
}
jonspaceharper
  • 4,207
  • 2
  • 22
  • 42