在 C++ 20 中,我们可以让编译器自动为我们生成 operator==
的实现(以及所有其他 default comparasions ,但我只对 感兴趣) > 运算符==
此处):
#include <compare>
struct Point {
int x;
int y;
bool operator==(const Point&) const = default;
};
有没有办法在 C++17 中实现相同的效果(自动生成 operator==
)?
由于库是一个不错的解决方案,我查看了 boost/operators 。下面的内容与上面的内容是等价的吗?
#include <boost/operators.hpp>
struct Point : boost<equality_comparable<Point, Point>> {
int x;
int y;
bool operator==(const Point&) const; // will this get auto-generated too and do the same as above?
};
最佳答案
仅适用于聚合(围绕 POD(简单+标准布局)类型稍微扩大的集合)。
使用 PFR 您可以 opt in using a macro :
Boost.PFR adds the following out-of-the-box functionality for aggregate initializable structures:
- comparison functions
- heterogeneous comparators
- hash
- IO streaming
- access to members by index
- member type retrieval
- methods for cooperation with std::tuple
- methods to visit each field of the structure
使用 BOOST_PFR_FUNCTIONS_FOR
的示例:
Defines comparison and stream operators for T along with hash_value function.
See Also : 'Three ways of getting operators' for other ways to define operators and more details.
<强> Live On Coliru
struct Point { int x, y; };
#include <boost/pfr.hpp>
BOOST_PFR_FUNCTIONS_FOR(Point)
#include <iostream>
#include <vector>
#include <set>
int main() {
std::vector pv { Point{1,2}, {2,1}, {-3,4}, {1,4/2}, {-3,-4} };
for(auto& p : pv) std::cout << p << " ";
std::cout << "\n";
std::set ps(begin(pv), end(pv));
for(auto& p : ps) std::cout << p << " ";
std::cout << "\n";
}
打印
{1, 2} {2, 1} {-3, 4} {1, 2} {-3, -4}
{-3, -4} {-3, 4} {1, 2} {2, 1}
严格使用c++14 (指定 vector<Point>
和 set<Point>
模板参数)。
关于c++ - 可以在 C++17 中模拟 C++2 0's ' operator==(const T&) = default' 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71815173/