gpt4 book ai didi

c++ - 这个长长的 "if argA == argB do ..."列表还有其他选择吗?

转载 作者:行者123 更新时间:2023-11-30 04:19:29 24 4
gpt4 key购买 nike

编辑:由于 attack.condition 偶尔会有多个值,switch 语句将不起作用!

所以我有这个枚举会增长:

enum Condition {    Null            =   0x0001,
SelfIsUnderground = 0x0002,
SelfIsGround = 0x0004,
SelfIsAir = 0x0008,
SelfIsWater = 0x0010,
OtherIsUnderground = 0x0020,
OtherIsGround = 0x0040,
OtherIsAir = 0x0080,
OtherIsWater = 0x0100,
Tile = 0x0200,
CONDITION_COUNTX = 0x03FF};

这个功能也将增长:

bool Attack::CanBeDone(Spirit* pSelf, Spirit* pTarget,Map* pMap)
{
if(this->condition!=Null)
{
if(this->condition & SelfIsUnderground)
if(pSelf->GetcurrentLayer()!=Underground)
return false;

if(this->condition & SelfIsGround)
if(pSelf->GetcurrentLayer()!=Ground)
return false;

if(this->condition & SelfIsAir)
if(pSelf->GetcurrentLayer()!=Air)
return false;

if(this->condition & SelfIsWater)
if(pSelf->GetcurrentLayer()!=Water)
return false;

if(this->condition & OtherIsUnderground)
if(pTarget->GetcurrentLayer()!=Underground)
return false;

if(this->condition & OtherIsGround)
if(pTarget->GetcurrentLayer()!=Ground)
return false;

...

有没有一种方法可以代替一遍又一遍地写:

    if(this->condition & arg)
if(pSelf->GetcurrentLayer()!=value)
return false;

?

奖励:如果我给 Condition::Null 值 0x0000、SelfIsUnderground 0x0001、SelfIsGround 0x0002 并再次使用 2 的幂,它会起作用吗?最终,Tile 将以值 0x0100 结束。

最佳答案

首先,我会写这样的东西:

enum Condition {    Null            =   0x0001,
SelfBase = 0x0002,
SelfIsUnderground = SelfBase * (1 << Underground),
SelfIsGround = SelfBase * (1 << Ground),
SelfIsAir = SelfBase * (1 << Air),
SelfIsWater = SelfBase * (1 << Water),
SelfMask = SelfBase * ((1 << Max) - 1),
OtherBase = 0x0020,
OtherIsUnderground = OtherBase * (1 << Underground),
OtherIsGround = OtherBase * (1 << Ground),
OtherIsAir = OtherBase * (1 << Air),
OtherIsWater = OtherBase * (1 << Water),
OtherMask = OtherBase * ((1 << Max) - 1),
Tile = 0x0200,
CONDITION_COUNTX = 0x03FF};

(假设 Underground == 0Max == Water + 1)。然后,长列表减少为两个相当清晰的表达式:

if ( (SelfMask & this->condition & (SelfBase * (1 << pSelf->GetcurrentLayer()))) )
return false;

if ( (OtherMask & this->condition & (OtherBase * (1 << pTarget->GetcurrentLayer()))) )
return false;

return true;

当您扩展枚举时,这仍然是正确的。但是请注意,仍然存在一些冗余(例如,如何定义 OtherBaseTile),这些冗余也可以减少。静态断言有助于确保 Condition 枚举定义明确。

关于c++ - 这个长长的 "if argA == argB do ..."列表还有其他选择吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15777404/

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