【问题标题】:How to choose class's operator== overloading over the template operator==?如何选择类的运算符==重载模板运算符==?
【发布时间】:2021-10-19 22:31:55
【问题描述】:

我已经为几种类型重载了operator==,同时使用模板和内联类方法。但是当谈到一个对象的引用时,lhs。将使用模板operator== 重载。为什么不在类定义中重载operator==

#include <iostream>

template <typename T0, typename T1>
bool operator==(const T0& lhs, const T1& rhs)
{
    std::cout << "Template == " << std::endl;
    return true;
}

struct Obj
{
    std::int32_t a;
    bool operator==(const Obj& rhs)
    {
        std::cout << "Obj == " << std::endl;
        return true;
    }
};

bool cmp(const Obj& obj) { return (obj == Obj{ 1 }); }

int main() {
    Obj a{ 2 };
    const Obj& b = a;
    cmp(a);
    cmp(b);
    a == b;
    b == a;
    return 0;
}

此代码给出以下结果:

Template ==
Template ==
Obj ==
Template ==

是否可以使用类内部定义的重载来强制编译器?

【问题讨论】:

  • 您的成员operator== 不是const 成员函数,不能以const Obj 作为其左侧来调用。
  • 我真的希望你的实际模板函数没有你在这里展示的那么广泛。此外,您可以(并且应该)将Obj::operator== 函数设为const
  • 因为你还没有将成员函数限定为const,所以模板版本更匹配。试试bool operator==(const Obj &amp;rhs) const {return true;};

标签: c++ function class templates operator-overloading


【解决方案1】:

是否可以强制编译器使用定义的重载 在课堂上?

是的,只需将operator== 重载为const 限定函数,这样它就会作用于Objconst 对象。

bool operator==(const Obj& rhs) const /* noexcept */
{
    std::cout << "Obj == \n";
    return a == rhs.a; // meaningful comparison
}

它选择模板重载是因为它是最佳匹配,它采用const 对象。

作为旁注,提供一个有意义的比较,类似于上面的内容。 See a demo

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-10-29
    • 2019-03-03
    • 2013-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-19
    相关资源
    最近更新 更多