c++ - 如何使用 std::rel_ops 自动提供比较运算符?

标签 c++ templates c++11 visual-studio-2012

<分区>

如何获取运算符 > , >= , <= , 和 !=来自 ==<

标准标题 <utility>定义一个命名空间 std::rel_ops,它根据运算符 == 定义上述运算符和 < ,但我不知道如何使用它(哄骗我的代码将此类定义用于:

std::sort(v.begin(), v.end(), std::greater<MyType>); 

我在其中定义了非成员运算符:

bool operator < (const MyType & lhs, const MyType & rhs);
bool operator == (const MyType & lhs, const MyType & rhs);

如果我#include <utility>并指定 using namespace std::rel_ops;编译器仍然提示 binary '>' : no operator found which takes a left-hand operand of type 'MyType' ..

最佳答案

我会使用 <boost/operators.hpp> 标题:

#include <boost/operators.hpp>

struct S : private boost::totally_ordered<S>
{
  bool operator<(const S&) const { return false; }
  bool operator==(const S&) const { return true; }
};

int main () {
  S s;
  s < s;
  s > s;
  s <= s;
  s >= s;
  s == s;
  s != s;
}

或者,如果您更喜欢非成员(member)运营商:

#include <boost/operators.hpp>

struct S : private boost::totally_ordered<S>
{
};

bool operator<(const S&, const S&) { return false; }
bool operator==(const S&, const S&) { return true; }

int main () {
  S s;
  s < s;
  s > s;
  s <= s;
  s >= s;
  s == s;
  s != s;
}

关于c++ - 如何使用 std::rel_ops 自动提供比较运算符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14756512/

相关文章:

c++ - 跳过 unordered_map 的第一次迭代

C++ 奇怪的 std::bad_alloc 异常

具有纯虚函数的模板类的 C++ 语法?

c++ - int arr[ ] 是有效的 C++ 吗?

C++ 模板显式实例化

c++ - 是否可以编写一个同时接受右值和左值的模板函数

C++:如何对 scoped_ptr 进行单元测试?

c++ - std::unordered_map::insert 的更简单形式?

c++ - 在 C 中为 Fortran 可分配内存分配内存

C++ Array of 120 ob​​jects with constructor + parameters, header- + sourcefile, no pointers please!