gpt4 book ai didi

c++ - 操作的条件运算符?

转载 作者:行者123 更新时间:2023-11-30 00:45:28 25 4
gpt4 key购买 nike

有条件运算符 x?a:b , 这通常可以节省大量的写作

现在我找到了这样的表达方式

   if ( ( isMax && lower-higher <= distance) ||
( !isMax && lower-higher >= distance) ) { ...

哪里
isMax是一个 bool 值,定义是使用最大值 (true) 还是最小值 (false),
lowerhigher是边界(在本例中为 int)

现在我想知道:有没有办法以这种方式“选择”运算符?

我的意思是不是可以选择操作数的“x?a:b”方式,而是使用不同的运算符

类似于bool (*op)() = isMax ? operator<=() : operator >= , 用于 lower-higher

或喜欢lower-higher (isMax? <= : >=) distance ,这是行不通的(当然)

最佳答案

简短回答:否。

但是接近的是编写你自己的具有这种效果的内联函数:

template<class T>
inline bool compare(bool isLessThan, const T& left, const T& right)
{
if (isLessThan) {
return left <= right;
}
else {
return left >= right;
}
}

// ... later ...
if (compare(isMax, lower - higher, distance)) {
// ...
}

我的意见(你没有要求):只需使用一个中间变量(或必要时使用几个)!

关于c++ - 操作的条件运算符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43207226/

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