【发布时间】: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 & 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);
};
【问题讨论】:
-
我不知道你是怎么测试的,但它对我有用,见here
-
PS:你确定要共享单位和价值吗..
-
您已经定义了同一个运算符两次。为什么要第三次定义它?您应该删除第一个定义。
-
我不想定义 3 个运算符。我想自动生成 1 == operator ,见编辑。
-
>PS:你确定要共享单位和价值为什么不呢?