操作的条件运算符?

时间:2017-04-04 12:26:37

标签: c++

有条件运算符x?a:b,它通常可以节省大量的文字

现在我发现了一个像这样的表达式

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

其中
isMax是一个bool,用于定义是否使用最大值(true)或最小值(false),而lowerhigher是边界(在这种情况下为int)

现在我想知道:有没有办法以某种方式&#34;选择&#34;操作员这样吗?

我的意思是&#34; x?a:b&#34;可以选择操作数的方式,但使用不同的操作符

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

或者像lower-higher (isMax? <= : >=) distance一样,当然不会工作

4 个答案:

答案 0 :(得分:2)

简短回答:不。

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

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)) {
    // ...
}

我的意见(你没有提出要求):只使用一个中间变量(如有必要,可以使用几个)!

答案 1 :(得分:2)

如果将运算符封装到具有相同类型的函数中,则可以执行此操作:

namespace detail{
template<class T>
bool less_equal(T lhs, T rhs)
{
    std::cout << "Using <=\n";
    return lhs <= rhs;
}

template<class T>
bool greater_equal(T lhs, T rhs)
{
    std::cout << "Using >=\n";
    return lhs >= rhs;
}
}

然后我们可以将你的逻辑编写为:

void DoTheThing(bool isMax, int lower, int higher, int distance)
{
    auto func = isMax ? &detail::less_equal<int> : &detail::greater_equal<int>;
    if (func(lower-higher, distance))
    {
        // your logic here
    }
}

测试:

int main()
{
    DoTheThing(true, 1, 1, 1); // <=
    DoTheThing(false, 1, 1, 1); // >=
    return 0;
}

输出:

Using <=
Using >=

Demo

答案 2 :(得分:1)

我不确定三元条件在这里有多大帮助。但是你可以通过编写

来节省一些打字(甚至可能获得一些性能;配置它)

private var _number: Int? public var number: NSNumber? { get { return _number as NSNumber? } set(newNumber) { _number = newNumber?.intValue } } // In case you want to set the number in the init public init(number: NSNumber?) { _number = number?.intValue }

这个假设(2 * isMax - 1) * (lower - higher) <= distanceisMax类型,或者是1或0.完全等同于钝角

bool

基于此理由,我需要进行3次编辑才能使其正确,这可能会侵犯可读性的边界。

也许因此保持原样,或将复杂性埋没在一个功能中。

答案 3 :(得分:1)

显然this is possible 1

(x ? [](int a, int b){ return a >= b; } : [](int a, int b){ return a <= b; })(a, b)

但是,你应该这样做吗?我个人只是使​​用(bool, int, int)功能。

1 我起初有些惊讶,但我猜它会以某种方式触发lambda衰变。如果它们是闭包(有[]内的东西),它们将是不同的类型,因此?:的类型将取决于运行时状态。

相关问题