C++ 动态评估变量类型布尔值



情况:我正在尝试实现两个类,一个称为"特殊"。special有一个成员变量bool conditions和一个方法perform_special。 另一个类名为manager,它作为special类型的成员变量。我希望manager只有在condition属实的情况下才对其special成员进行perform_special

到目前为止,我已经实现了这段代码:

#include<iostream>
using namespace std;
class special{
public:
special(){};
void perform_special();
void set_conditions( bool cond );
bool get_conditions();
private:
bool conditions;
};
void special::perform_special(){ cout<<"special performed."<<endl; }
void special::set_conditions( bool cond ){ conditions = cond; }
bool special::get_conditions(){ return conditions; }
class manager{
public:
manager(){};
void check_specials();
void set_effect( special* eff );
private:
special* effect;
};
void manager::check_specials(){
if(effect->get_conditions()){ effect->perform_special(); }
}
void manager::set_effect( special *eff ){ effect = eff; }
int main(){
int a=3; int b=2;
bool cond = a<b;
special effect1;
effect1.set_conditions( cond );
a=2; b=3;
manager manager1;
manager1.set_effect( &effect1 );
manager1.check_specials();
return 0;
}

这就是它的作用:它创建布尔cond立即被评估为false,因为此时a<b为假。现在,它将此条件提供给一个特殊变量,该变量再次提供给管理器变量。当管理器对其特殊变量调用check_special时,不会发生任何反应,因为cond为 false。

这是我的问题:我不希望立即评估cond。正如您在代码中看到的,a 和 be 的值可能会更改,因此表达式的值可能会更改a<b。如何实现仅在调用函数check_specials()并使用变量 a 和 b 的最新值时才计算cond的值?

背景:我正在尝试实现一个基于文本的冒险游戏,所以"特殊"将是某种特殊效果,如果一堆条件为真,就会发生。"经理"将是某种大师班,负责处理游戏并拥有所有特效等。我想在 main 函数中声明这些特殊效果并将它们传递给manager类型的变量"game",然后启动游戏的例程,所以我需要manager动态评估特殊效果的条件表达式,因为条件显然会随着时间的推移而变化。

你可以构建一个Cond类,原型如下:

struct Cond
{
int& a;
int& b;
operator bool() const {return a < b;}
};

你会实例化

Cond cond{a, b};

代替您当前的cond声明。

然后,您将在测试点编写if (cond),这将使用当前值a并通过引用b

这就是这种懒惰评估技术的骨头,但这仅仅是个开始。主要陷阱是悬而未决的引用的可能性,也许可以用std::reference_wrapper来解决。

您将bool类型的变量传递给方法cond()并且变量只能保存值。你需要传递的是一个函数,它返回bool

class special{
public:
using predicate = std::function<bool()>;
void set_conditions( predicate p );
...
};

现在你可以传递一个函数、函子、lambda 等,稍后会对其进行评估:

int main()
{
int a=3; int b=2;
auto cond = [&]{ return a<b; };
special effect1;
effect1.set_conditions( cond );
...
}

相关内容

最新更新