【发布时间】:2015-07-30 15:15:41
【问题描述】:
我使用作用域枚举创建位标志,并重载 operator | 以组合值:
enum class PARAM_T : int {
NONE = 0x0,
INPUT = 0x01,
OUTPUT = 0x02,
OUTPUT_VECTOR = 0x04
};
inline PARAM_T operator | (PARAM_T lhs, PARAM_T rhs)
{
using T = std::underlying_type_t<PARAM_T>;
return (PARAM_T)(static_cast<T>(lhs) | static_cast<T>(rhs));
}
在我项目的其他地方,我使用 Qt 小部件进行一些拖放操作,其中我使用 operator | 来组合一些命名常量:
Qt::DropAction dropAction = drag->exec(Qt::CopyAction | Qt::MoveAction);
这里的operator | 与我的位标志无关,但由于某种原因,我的重载破坏了这行代码,出现以下错误:
error C2664: 'Qt::DropAction QDrag::exec(Qt::DropActions,Qt::DropAction)' : cannot convert argument 1 from 'int' to 'Qt::DropActions'
为什么编译器会将 Qt 常量与我的重载相匹配?它们是完全不同且不兼容的类型。
【问题讨论】:
-
这看起来不可能。你能提供一个 MCVE 吗?
-
我无法重现我的 MCVE 的问题。我试图弄清楚我必须添加哪些代码才能使其失败,因为它在我的项目中失败了。顺便说一句,这看起来不可能怎么办?
-
您应该使用
QFlags,然后您将获得类型安全和运算符,即使在 C++98 上也是如此。 -
它适用于 Qt 5.5/mingw 4.9.2/std=c++14 标志。 “这看起来不可能怎么办?”:您的问题,正是因为“它们是完全不同的类型”(尽管您可以使用
static_cast<>)。建议使用QFlags作为变通方法,不要放弃枚举。
标签: c++ qt enums operator-overloading