将变体的替代类型放入子命名空间似乎会破坏operator==
:
#include <variant>
#include <iostream>
namespace NS {
namespace structs {
struct A {};
struct B {};
} // namespace structs
using V = std::variant<structs::A, structs::B>;
bool operator==(const V& lhs, const V& rhs)
{
return lhs.index() == rhs.index();
}
std::string test(const V& x, const V& y)
{
if (x == y) {
return "are equal";
} else {
return "are not equal";
}
}
namespace subNS {
std::string subtest(const V& x, const V& y)
{
if (x == y) {
return "are equal";
} else {
return "are not equal";
}
}
} // namespace subNS
} // namespace NS
int main() {
const auto u = NS::V{NS::structs::A{}};
const auto v = NS::V{NS::structs::A{}};
const auto w = NS::V{NS::structs::B{}};
// Why doesn't this work?
// It does work if A and B are defined in NS rather than NS::structs.
//std::cout << "u and v are " << (u == v ? "equal" : "not equal") << "\n";
//std::cout << "u and w are " << (u == w ? "equal" : "not equal") << "\n";
std::cout << "u and v " << NS::test(u, v) << "\n";
std::cout << "u and w " << NS::test(u, w) << "\n";
std::cout << "u and v " << NS::subNS::subtest(u, v) << "\n";
std::cout << "u and w " << NS::subNS::subtest(u, w) << "\n";
}
我找到的唯一解决方案是定义:
namespace std {
template<>
constexpr bool
operator==(const NS::V& lhs, const NS::V& rhs)
{
return lhs.index() == rhs.index();
}
} // namespace std
但这看起来有点可疑,并且似乎被 c++20 禁止:https ://en.cppreference.com/w/cpp/language/extending_std#Function_templates_and_member_functions_of_templates
有更好的想法吗?显然,我试图避免operator==
为每种替代类型添加。