lin*_*ver 1 c++ optional comparison-operators c++17
根据此,使用了比较运算符上的optional<T>和optional<U>应该工作条件是相同的运营商是为基础类型定义T和U.
我正在尝试以下示例,其中两个枚举在不同的命名空间中定义(这里是实时代码),并且无法弄清楚为什么它无法编译:
#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);
}
Run Code Online (Sandbox Code Playgroud)
我的GCC-8.2.0说:
invalid operands to binary expression ('const std::optional<n1::tag>' and 'const std::optional<n2::tag>')
有任何想法吗?我发现将每个枚举移出其命名空间,事情按预期工作(如此处).
该<运营商必须在任何关联的命名空间的它的参数,即它必须位于命名空间n1或n2不过既然n2::tag是不是在定义可见n1::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);
}
}
Run Code Online (Sandbox Code Playgroud)
开放的命名空间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);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
108 次 |
| 最近记录: |