c++ - 如何使用 boost/operators.hpp 自动生成 == 运算符?

标签 c++ c++11 boost

从这里跟进,因为我问的是一个稍微不同的问题: 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 会自动实现运算符 ==,但编译器提示缺少实现错误。如何自动实现以下功能:

bool operator == (const Base & lhs, const Base & 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);
};

最佳答案

boost::equality_comparable<T>期待 T提供operator== , 并提供 operator!=基于此。它不会神奇地知道如何比较任意类。就在那里in the reference you cite - 注意“要求”列和“提供的操作”列中的内容。

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

关于c++ - 如何使用 boost/operators.hpp 自动生成 == 运算符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58261272/

相关文章:

c++ - 如何在C++ 11中使用boost::optional进行重写?

c++ - boost.Geometry 中面积的三角测量

c++ - 读取存储在 double 中的 8 字节字段的 4 个字节

c++ - 使用 vector::push_back 移动

c++ - 将着色器与 directx 11 相结合

c++ - 使用 shared_ptr 和 glutInit 导致段错误

c++ - 在 boost geometry c++ 库中我添加的点的顺序有关系吗?

c++ - Boost.Asio - 轮询命名管道

c++ - 将文件存储在 unsigned char 数组中并打印

java - JNI 我可以使用哪些类型而不是给定的类型(unsigned int、const char*、const wchar_t*、....)