标准::可选枚举的比较运算符



据此,在optional<T>optional<U>上使用比较运算符应该可以工作,前提是为TU的基础类型定义了相同的运算符。

我正在使用在不同命名空间中定义的两个枚举(此处为实时代码(尝试以下示例,但无法弄清楚为什么它无法编译:

#include <optional>
namespace n1
{
enum class tag : unsigned {I,II,III};
}
namespace n2
{
enum class tag : unsigned {I,II,III};
}
bool operator<(const n1::tag& t1, const n2::tag& t2)
{
return static_cast<unsigned>(t1) < static_cast<unsigned>(t2);
}
int main()
{
const std::optional<n1::tag> o1(n1::tag::I);
const std::optional<n2::tag> o2(n2::tag::I);
bool t = (o1 < o2);
}

我的GCC-8.2.0说:

invalid operands to binary expression ('const std::optional<n1::tag>' and 'const std::optional<n2::tag>')

有什么想法吗?我发现将每个枚举移出其命名空间,事情会按预期工作(如此处(。

<运算符必须位于其参数的任何关联命名空间中,即它必须位于命名空间n1n2中,但由于n2::tagn1::tag的定义中不可见,您需要将运算符放在命名空间n2或重新打开命名空间n1

在命名空间n2中定义运算符:

namespace n2
{
enum class tag : unsigned {I,II,III};
bool operator<(const n1::tag& t1, const n2::tag& t2)
{
return static_cast<unsigned>(t1) < static_cast<unsigned>(t2);
}    
}

打开命名空间n1

...
namespace n2
{
enum class tag : unsigned {I,II,III};
}
namespace n1 {
bool operator<(const n1::tag& t1, const n2::tag& t2)
{
return static_cast<unsigned>(t1) < static_cast<unsigned>(t2);
}        
}

最新更新