【问题标题】:How do I automatically generate the == operator with boost/operators.hpp?如何使用 boost/operators.hpp 自动生成 == 运算符?
【发布时间】:2020-02-04 06:14:55
【问题描述】:

由于我问的是一个略有不同的问题,因此请继续跟进: What's the difference between using boost::equality_comparable<T> versus overriding bool operator ==?

这是我尝试编写的代码。

#include <boost/operators.hpp>

enum class AnEnum : uint64_t;

struct Base : boost::equality_comparable<Base, Base> {
    std::shared_ptr<AnEnum > units;

    std::shared_ptr<int> value;

    bool operator ==(Base const& rhs) { 
        return (*value == *rhs.value)
            && (*units == *rhs.units); 
    }

    friend bool operator == (const Base & lhs, const Base & rhs) {
        return (*lhs.value == *rhs.value)
            && (*lhs.units == *rhs.units);
    };
};

我希望 Boost 会自动实现 operator == 但编译器抱怨缺少实现错误。如何自动实现以下功能:

bool operator == (const Base &amp; lhs, const Base &amp; rhs);

我以此为参考:https://www.boost.org/doc/libs/1_71_0/libs/utility/operators.htm#arithmetic

编辑:

如何自动定义 == 运算符,如下所示:

#include <boost/operators.hpp>

enum class AnEnum : uint64_t;

struct Base : boost::equality_comparable<Base, Base> {
    std::shared_ptr<AnEnum > units;

    std::shared_ptr<int> value;

    friend bool operator == (const Base & lhs, const Base & rhs);
};

【问题讨论】:

  • 我不知道你是怎么测试的,但它对我有用,见here
  • PS:你确定要共享单位和价值吗..
  • 您已经定义了同一个运算符两次。为什么要第三次定义它?您应该删除第一个定义。
  • 我不想定义 3 个运算符。我想自动生成 1 == operator ,见编辑。
  • >PS:你确定要共享单位和价值为什么不呢?

标签: c++ c++11 boost


【解决方案1】:

boost::equality_comparable&lt;T&gt; 期望T 提供operator==,并基于此提供operator!=。它并不神奇地知道如何比较任意类。它就在in the reference you cite - 请注意需求列和供应操作列中的内容。

boost::equality_comparable&lt;Base, Base&gt; 有点毫无意义。 equality_comparable 的双参数形式旨在综合不同类型对象之间的异构比较。

【讨论】:

  • 是否可以自动生成header的实现:bool operator == (const Base &amp; lhs, const Base &amp; rhs);
  • 您为什么想要operator== 的成员和非成员版本?两者都提供是没有意义的——如果你这样做了,任何实际比较两个实例的尝试都会产生“模棱两可的重载”错误。选择一个并坚持下去。
  • 另外,您希望operator== 的成员版本为const,如bool operator ==(const Base&amp; rhs) const;
  • >为什么要同时使用 operator== 的成员和非成员版本?请参阅编辑,我不想同时提供两者。 const 还有什么作用?
  • std::shared_ptr 既不是原语也不是枚举,而是类类型的对象。此外,这个类确实提供了operator==,它 not 做你似乎期望的事情(它比较两个原始指针,而不是指向的对象)。因此,您假设的 Equatable 在您的示例中可能效果不佳。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-05-16
  • 2011-02-26
  • 2012-06-27
  • 1970-01-01
  • 2021-04-04
  • 2022-01-13
  • 1970-01-01
相关资源
最近更新 更多