static_cast对getInt()函数有意义吗

Does a static_cast make sense on a getInt() function?

本文关键字:函数 有意义 getInt cast static      更新时间:2023-10-16

对于这种明显的情况,这种统计强制转换有意义吗?

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

还是静态强制转换用于源类型不确定为int的情况?

设置的功能是

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

简单铸造有什么好处?

obj.setMyEnumType((MyEnumType)q.value(2).toInt());

是的,演员阵容非常合理。让我们再解开这个:

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.

编辑:啊哈!我知道你现在在问一个完全不同的问题。你真正问的问题是static_cast<gt;和C型铸造?

总是更喜欢static_cast,因为a)代码评审员会被提示思考"如果值超出范围会发生什么?";b) 代码评审员不必思考"这是静态强制转换、重新解释强制转换、常量强制转换还是这三者的组合?"

在这种情况下,您的问题有点像XY问题,因为QVariant提供了内置的转换安全检查和强制转换。

使用qvariant_castQVariant::value<>()canConvert(),例如:

QVariant v = q.value(2);
if (v.canConvert<MyEnumType>()) {
    obj.setEnumType( qvariant_cast<MyEnumType>(v));
    ...
}

int转换为enum并返回非常合理。您可以检查边界条件(例如,int大于枚举的最后一个元素)。请注意,这里不是强制转换函数,而是返回值。