我正在使用 C++0x 的 lambdas 来定义 boost 函数。我有一些类,我使用 lambdas/boost 函数定义它们的一些行为。我想知道的是,是否可以在不更改函数定义的情况下将有关类的数据公开到 lambda 的上下文中?例如,我有一组这样的类:
class ConsumableItem : public Item
{
public:
//Constructors here
virtual bool Use(std::set<Character::BaseCharacter*> Users, std::set<Character::BaseCharacter*> Targets);
virtual bool Use(std::set<Battles::BattleCharacter> Users, std::set<Battles::BattleCharacter> Targets, Battles::BattleField &field);
protected:
bool UseRegularFunction;
boost::function<void(std::set<Character::BaseCharacter*>, std::set<Character::BaseCharacter*>)> RegularUse;
bool UseBattleFunction;
boost::function<void(std::set<Battles::BattleCharacter>, std::set<Battles::BattleCharacter>, Battles::BattleField &)> BattleUse;
};
class StatBoostingItem : public ConsumableItem
{
public:
StatBoostingItem(int UID, std::string &name, std::string &descript, boost::unordered_set<ItemFlags> Flags, boost::unordered_map<Stat, int> &boosts, int value);
protected:
virtual bool Use(std::set<Character::BaseCharacter*> Users, std::set<Character::BaseCharacter*> Targets) override;
virtual bool Use(std::set<Battles::BattleCharacter> Users, std::set<Battles::BattleCharacter> Targets, Battles::BattleField &field) override;
private:
boost::unordered_map<Stat, int> StatBoosts;
}
在 stat boosting item 的构造函数中,我希望能够做到这一点:
StatBoostingItem::StatBoostingItem(int UID, std::string &name, std::string &descript, boost::unordered_set<ItemFlags> Flags, boost::unordered_map<Stat, int> &boosts, int value)
: ConsumableItem(UID, name, descript, Flags, ItemClass::STAT_BOOSTING_ITEM, value)
{
StatBoosts = boosts;
RegularUse = [](std::set<Character::BaseCharacter*> users, std::set<Character::BaseCharacter*> targets)
{
for (auto character = targets.begin(); character != targets.end(); ++character)
{
for (auto statBoost = StatBoosts.begin(); statBoost != StatBoosts.end(); ++statBoost)
{
//Item Effect in here
}
}
};
}
这更像是一件好奇的事情,因为我知道我可以简单地扩展 boost::function 定义以包含指向相关项目的指针并以这种方式获取数据,或者覆盖我的 Use 函数。但是,如果我能以某种方式将有关包含它的类的信息公开到 lambda 中,那将是理想的,因为我也可以在其他地方使用它