C++多可能值控制流

C++ Multiple Possible Value Control Flow

本文关键字:控制流 C++      更新时间:2024-09-28

当前使用C++20,GCC 11.1.0

我正在为游戏循环中的简单动作编码。

按照下面的抽象伪代码,我该如何将其翻译成代码?我想使用goto直接跳到使用值的范围中,或者使用std::optional检查值是否存在。

我之所以尝试这样做,而不是仅仅将底部if语句添加到A…D if语句中,是因为底部if语句可能会变得非常大,并且可能会增加冗余。还是应该将if语句重构为一个单独的函数?

if (direction is left && ...)
{
int xVelocity {left_calculation...};
}
else if (direction is right && ...)
{
int xVelocity {right_calculation...};
}
else if (direction is up && ...)
{
int yVelocity {up_calculation...};
}
else if (direction is down && ...)
{
int yVelocity {down_calculation...};
}

if (x has a value or y has a value)
{
// Do something with those values...
}

您可以通过std::option:表示可选性

std::optional xVelocityOpt =
direction == left  ? std::make_optional(left_calculation)
: direction == right ? std::make_optional(right_calculation)
: {};
std::optional yVelocityOpt =
direction == up    ? std::make_optional(up_calculation)
: direction == down  ? std::make_optional(down_calculation)
: {};
if (xVelocityOpt || yVelocityOpt)
{
// you can use the actual values as
// *xVelocityOpt and *yVelocityOpt
// ...
}

但我也会考虑使用简单的int速度,并将空表示为0(如果你所说的变量在物理学中是delta v(。

如果使用delta_x,delta_y来改变相对值,那么问题就会自行解决。那么你的if只是:

int delta_x = 0;
int delta_y = 0;
...
if( delta_x | delta_y )
on_xy_changed(old_x + delta_x, old_y + delta_y);