c++ - 可以在 C++17 中模拟 C++2 0's ' operator==(const T&) = default' 吗?

标签 c++ boost c++17 comparator

在 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/

相关文章:

c++ - std::exception 使用来自本地对象的消息

c++ - header `execution` 和 `std::reduce` 未找到

c - 是否有一个用 C 编写的分词器函数可以完成 boost::escaped_list_separator 的功能?

c++ - 在现代 C++ 中是否可以将字符串文字作为参数传递给 C++ 模板?

c++ - 不合格的 sort() ——为什么它在 std::vector 上使用时编译,而不是在 std::array 上使用,哪个编译器是正确的?

c++ - 复制省略直接基类初始化?

c++ - OpenGL错误编译着色器

c++ - 打印对象数组

c++ - 我应该如何在 C++ 中读取和解析(真实的、正确的、全功能的)CSV?

c++ - 如何使用 boost::interprocess::vector 在共享内存中分配复杂的结构?