C++:有没有什么方法可以让条件运算符基于一个值来简化代码块?

C++: Is there any way to have conditional operators based on a value in order to simplify blocks of code?

比如说:

if(CurrentRotationStage % 2 == 0)
{
    if(FMath::CubicInterpDerivative(CubicPoint[CurrentRotationStage], 0.f, CubicPoint[(CurrentRotationStage + 1) % 4], 0.f, MainMenuWidget->TrumpAngle / RotationLimit) < 0.f)
    {
        CurrentRotationStage = ++CurrentRotationStage % 4;
        MainMenuWidget->TrumpAngle -= RotationLimit;
    }
}
else
{
    if(FMath::CubicInterpDerivative(CubicPoint[CurrentRotationStage], 0.f, CubicPoint[(CurrentRotationStage + 1) % 4], 0.f, MainMenuWidget->TrumpAngle / RotationLimit) > 0.f)
    {
        CurrentRotationStage = ++CurrentRotationStage % 4;
        MainMenuWidget->TrumpAngle -= RotationLimit;
    }
}

基本上,如果 CurrentRotationStage 是偶数,我想在我的 if 语句中使用 <,如果它是奇数,则相反。有什么方法可以简化这个以防止使用多个 if/elses?

这部分应该放在一个变量中。

(FMath::CubicInterpDerivative(CubicPoint[CurrentRotationStage], 0.f, CubicPoint[(CurrentRotationStage + 1) % 4], 0.f, MainMenuWidget->TrumpAngle / RotationLimit)

然后它看起来像这样:

blah = calculateIt...
if(CurrentRotationStage % 2 == 0 && blah < 0.f) ||
 (CurrentRotationStage % 2 != 0 && blah > 0.f){
    CurrentRotationStage = ++CurrentRotationStage % 4;
    MainMenuWidget->TrumpAngle -= RotationLimit;
}

将比较逻辑拉入普通函数或class

class RotationChecker
{
public:
    explicit RotationChecker(int stage): stage_(stage) {}
    bool operator()(float f) const { return stage % 2 == 0 ? f < 0.f : f > 0.f; }
private:
    int stage_;
};

RotationChecker checker(CurrentRotationStage);
float value = FMath::CubicInterpDerivative(CubicPoint[CurrentRotationStage], 0.f,
    CubicPoint[(CurrentRotationStage + 1) % 4], 0.f,
    MainMenuWidget->TrumpAngle / RotationLimit);
if (checker(value)))  // or "if (RotationChecker(CurrentRotationStage)(value))"
{
    CurrentRotationStage = ++CurrentRotationStage % 4;
    MainMenuWidget->TrumpAngle -= RotationLimit;
}

一般来说,如果你想要一个可切换的运算符,就像这样:

#include <iostream>
#include <algorithm>
#include <functional>

int main() {
    std::function<bool(int,int)> op = std::less<int>();
    std::cout << "Defaulting to less-than" << std::endl;

    int x = 5;
    if (x & 1) {
        op = std::greater<int>();
        std::cout << "Chosing greater-than because number is odd" << std::endl;
    }

    if (op(x, 4)) {
        std::cout << x << " is op(4)" << std::endl;
    }
}

我会采用一些现有答案中的方法:

std::function<bool (int, int)> fn = std::less<int>();
if (CurrentRotationStage % 2 == 0)
{
    fn = std::greater<int>();
}

float result = FMath::CubicInterpDerivative(CubicPoint[CurrentRotationStage], 0.f, CubicPoint[(CurrentRotationStage + 1) % 4], 0.f, MainMenuWidget->TrumpAngle / RotationLimit);

if (fn(result, 0.f))
{
    CurrentRotationStage = ++CurrentRotationStage % 4;
    MainMenuWidget->TrumpAngle -= RotationLimit;
}