static_cast对getInt()函数有意义吗
Does a static_cast make sense on a getInt() function?
对于这种明显的情况,这种统计强制转换有意义吗?
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_cast
或QVariant::value<>()
和canConvert()
,例如:
QVariant v = q.value(2);
if (v.canConvert<MyEnumType>()) {
obj.setEnumType( qvariant_cast<MyEnumType>(v));
...
}
从int
转换为enum
并返回非常合理。您可以检查边界条件(例如,int大于枚举的最后一个元素)。请注意,这里不是强制转换函数,而是返回值。
相关文章:
- 在C++中,使用带有 std::optional 参数的函数<T>来表示可选参数是否有意义?
- sizeof(函数)有意义吗?
- 插入向量时,使用lambda的返回而不是函数的返回是否有意义?
- 将指针的地址传递给需要指针到指针的函数有什么意义?
- 内联这个函数,确实有意义
- 将 final 关键字添加到没有基类(未派生)的类中的虚函数是否有意义
- 函数返回rvalue参考是否有意义
- 删除默认类构造函数有什么意义?
- 将 [[noreturn]] 添加到主函数是否有意义
- 拥有一个没有构造函数的类是否有意义
- constexpr移动构造函数是否有意义
- 在不提供定义的情况下重写函数有什么意义?
- Arduino C++:F()宏在函数内部有意义吗
- 初始化对象后,用隐式转换而不是赋值运算符调用构造函数有什么意义
- 具有多个非可选参数的转换构造函数是什么样子的?为什么它有意义
- 从 STL 容器继承并删除"新"运算符以防止由于缺少虚拟析构函数而导致未定义的行为是否有意义?
- 在某些情况下无法返回有意义值的 C++ 函数
- 在动态内存上操作,重载constmemeber函数有意义吗
- 这就是为什么 C++ 11 中的移动构造函数有意义
- static_cast对getInt()函数有意义吗