我正在尝试在引导程序调用中使用引导程序。这有效:
void calc_equipment(auto &gamedata, auto &player)
{
player.equipment.STR += gamedata.items[gamedata.equipment[player.total.id].weapon.STR;
player.equipment.STR += gamedata.items[gamedata.equipment[player.total.id].armor.STR;
}
但这不是:
void calc_equipment(auto &gamedata, auto &player)
{
vector<string> types;
types.resize(2);
types[0] = "weapon";
types[1] = "armor";
player.equipment.STR += gamedata.items[gamedata.equipment[player.total.id].types[0].STR;
player.equipment.STR += gamedata.items[gamedata.equipment[player.total.id].types[1].STR;
}
显然,这种方式行不通,但是有人可以指出我正确的方向吗?如何构造和使用types []检索正确的数据?我可以使用整数而不是字符串,但是它也不起作用。最终目标是迭代这些计算,而不是手动将其写出。
干杯!
答案 0 :(得分:0)
您的示例是much more complicated than it had to be,但是您似乎想通过包含变量名的字符串来操作变量。我不记得这种方法的名称,但是C ++不支持它。
我认为最好的方法(如果您真的想这样做)将是一个包装器,该包装器通过索引运算符使结构的成员可用。
class EquipmentWrapper
{
public:
EquipmentWrapper(Equipment &nE): E(nE)
{}
int operator[](unsigned int k) const
{
switch(k)
{
case 0: return E.weapon;
case 1: return E.armor;
default: throw(0);
}
}
private:
Equipment &E;
};
...
EquipmentWrapper W(gamedata.equipment[player.total.id]);
player.equipment.STR += W[0].STR;
player.equipment.STR += W[1].STR;
答案 1 :(得分:0)
听起来您想以反射的方式迭代结构的字段。 Beta中没有内置支持。
您可以使流运算符过载您的项目类型以及称为设备的项目的常规集合。每个结构都知道如何对其进行字符串化。您的客户代码仅要求顶级设备将其自身插入流中。下面的示例:
using namespace std;
struct Weapon
{
Weapon(string const & nm) : name(nm) {}
string name;
};
ostream& operator<<(ostream & os, Weapon const & w)
{
os << w.name;
return os;
}
struct Armor
{
Armor(string const & nm) : name(nm) {}
string name;
};
ostream& operator<<(ostream & os, Armor const & a)
{
os << a.name;
return os;
}
struct Equipment
{
Equipment(Weapon const & _w, Armor const & _a) : w(_w), a(_a) {}
Weapon w;
Armor a;
};
ostream& operator<<(ostream & os, Equipment const & e)
{
os << e.w << ", " << e.a;
return os;
}
int main()
{
Weapon w("sword of smiting");
Armor a("plate of deflection");
Equipment e(w, a);
//can be sstream just as well to collect into a string
cout << e << endl;
}