C++20 的"运算符==(const T&) = default"可以在 C++17 中最小化吗?



在C++20中,我们可以让编译器自动为我们生成operator==的实现,如下所示(以及所有其他默认比较,但我只是对operator==感兴趣(:

#include <compare>
struct Point {
int x;
int y;
bool operator==(const Point&) const = default;
};

有没有一种方法可以在C++17中归档相同的内容(自动生成operator==(?

由于库是一个不错的解决方案,我研究了boost/运算符。以下内容与上述内容等效吗?

#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,您可以选择使用宏:

Boost.PFR为聚合可初始化结构:

  • 比较函数
  • 异构比较器
  • 散列
  • IO流
  • 按索引访问成员
  • 成员类型检索
  • 与std::tuple合作的方法
  • 访问结构每个字段的方法

使用BOOST_PFR_FUNCTIONS_FOR:的示例

定义T的比较运算符和流运算符以及hash_value作用

另请参阅:"获取运算符的三种方法"以了解其他定义方法操作员和更多详细信息。

在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>模板参数(。

最新更新