gpt4 book ai didi

c++ - 在三元中使用 std::greater 和 std::greater_equal

转载 作者:太空宇宙 更新时间:2023-11-03 10:28:22 28 4
gpt4 key购买 nike

我正在使用 std::find_if作为第三个参数,我想在 std::bind2nd 中使用三元组:

std::bind2nd(foo ? std::greater<K>() : std::greater_equal<K>(), bar);

对于某些类型 K . foobool旗帜。但这在语法上是不正确的,因为 std::greater<K>()std::greater_equal<K>()是不同的类型。

理想情况下,我想删除三元组(因为上面的循环针对各种 bar s 运行)并且有

auto predicate = foo ? std::greater<K>() : std::greater_equal<K>();
std::bind2nd(predicate, bar); /*this statement is in a loop*/

但这作为 predicate 的类型也是不合法的在编译时不知道。但是std::bind2nd可以采用任何一种类型,所以我的想法是可能是一种实现我想要的东西的方法。有吗?

最佳答案

使相同类型的操作数:

auto predicate = foo
? std::function<bool(K,K)>(std::greater<K>())
: std::function<bool(K,K)>(std::greater_equal<K>());

DEMO

理由:

§ 5.16 Conditional operator [expr.cond] / p3

[...] if the second and third operand have different types and either has (possibly cv-qualified) class type, or if both are glvalues of the same value category and the same type except for cv-qualification, an attempt is made to convert each of those operands to the type of the other.

std::greater<K>()之间没有转换和 std::greater_equal<K>()编译器可以自行执行。

关于c++ - 在三元中使用 std::greater<K> 和 std::greater_equal<K>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25661223/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com