C++多可能值控制流
C++ Multiple Possible Value Control Flow
当前使用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);
相关文章:
- 是否可以使用if constexpr删除控制流语句
- 控制多线程程序中的输出流
- 如何从 SYCL 内核中提取控制流?
- 控制开关语句的流而不中断
- 如何使用boost::asio::serial_port支持硬件流控制
- C++中的流控制结构,如何修改
- c++,除非用于流控制的包装器构造
- 使用condition_variable控制多线程流
- 如何使用硬件流控制进行提升::ASIO::serial_port_base::flow_control
- 有没有办法创建一个公共输出流对象以在控制台上打印并打印到 c++ 中的文件
- 生产编译器如何在流控制上实现析构函数处理
- 流运算符和控制转换优先级
- 控制流图生成器的c++代码
- 这个流控制关键字类标识符的结构是什么?
- C++(或任何其他语言)中的优雅控制流
- gcc-gprof/gcov/other-如何获取函数调用/出口+控制流语句的序列
- 在线程间的控制流中使用不带互斥锁的非原子布尔值是否安全?
- 如何创建控制流?C++
- GCC中枚举开关的控制流分析不足
- 混淆控制流分析从Parasoft c++测试