有什么可以一般地反转 C++ Comparator 类型吗?
Is there anything to generically invert a C++ Comparator type?
例如,如果我传入 std::less
,我希望它创建一个行为等于 std::greater
的新比较器。用于模板。
可以启用像 std::map<int, int, std::invert<std::less>>
这样的语法的东西(除非我正在寻找的东西存在,那不是它的名字)。这个存在吗?
有std::not_fn
,which:
Creates a forwarding call wrapper that returns the negation of the callable object it holds.
但是,在这种情况下,它会导致比较器具有 std::greater_equal
的功能,而不是 std::greater
。此外,类型与 std::greater_equal
.
不同
示例:
auto greater_eq = std::not_fn(std::less<>());
要获得 std::greater
的等价物,您可以通过翻转参数来获得它。我不认为标准库中有这样的函数,但是自己写很简单:
auto flip = [](auto fun) {
return [fun = std::move(fun)]
(const auto& arg1, const auto& arg2)
{
return fun(arg2, arg1);
};
};
auto greater = flip(std::less<>());
这也可以扩展为支持任意数量的参数,仅翻转前两个(使其类似于 Haskell 中的 flip
),以及支持参数的完美转发,但是这些功能可能会使简洁的示例变得相当复杂,并且比较器不需要这些功能。
例如,如果我传入 std::less
,我希望它创建一个行为等于 std::greater
的新比较器。用于模板。
可以启用像 std::map<int, int, std::invert<std::less>>
这样的语法的东西(除非我正在寻找的东西存在,那不是它的名字)。这个存在吗?
有std::not_fn
,which:
Creates a forwarding call wrapper that returns the negation of the callable object it holds.
但是,在这种情况下,它会导致比较器具有 std::greater_equal
的功能,而不是 std::greater
。此外,类型与 std::greater_equal
.
示例:
auto greater_eq = std::not_fn(std::less<>());
要获得 std::greater
的等价物,您可以通过翻转参数来获得它。我不认为标准库中有这样的函数,但是自己写很简单:
auto flip = [](auto fun) {
return [fun = std::move(fun)]
(const auto& arg1, const auto& arg2)
{
return fun(arg2, arg1);
};
};
auto greater = flip(std::less<>());
这也可以扩展为支持任意数量的参数,仅翻转前两个(使其类似于 Haskell 中的 flip
),以及支持参数的完美转发,但是这些功能可能会使简洁的示例变得相当复杂,并且比较器不需要这些功能。