覆盖 std::variant::operator==

我有点惊讶将变体的替代类型放入子命名空间似乎打破了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==为每个替代类型添加。

N·斯黑德

原因是由于ADL。特别是,请参阅[basic.lookup.argdep]/2 :(强调我的)

对于函数调用中的每个参数类型 T,需要考虑一组零个或多个关联命名空间和一组零个或多个关联实体(命名空间除外)。命名空间和实体的集合完全由函数参数的类型(以及任何模板模板参数的命名空间)决定。用于指定类型的 Typedef 名称和 using 声明对这个集合没有贡献。命名空间和实体的集合按以下方式确定:

  • ...
  • 如果 T 是一个类类型(包括联合),它的关联实体是: 类本身它所属的班级,如果有的话;及其直接和间接基类。它的关联命名空间是其关联实体的最内部封闭命名空间。此外,如果 T 是类模板特化,则其关联的命名空间和实体还包括:与为模板类型参数提供的模板实参类型关联的命名空间和实体(不包括模板模板参数);用作模板模板参数的模板;任何模板模板参数是其成员的命名空间;以及用作模板模板参数的任何成员模板都是其成员的类。

特别是,“using-declaration”V存在的::NS事实不会影响依赖参数的查找。被认为是命名空间::std,从std::variant::NS::structs,从<structs::A, structs::B>模板参数。

NS::test并且NS::subNS::subtest工作,因为他们不需要依赖 ADL 来查找operator==包含在NS.

正如评论中已经提到的那样,解决方案operator==将被定义在可以找到的地方 - 在这种情况下,将在::NS::structs.

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章