从字符串访问字段?

时间:2012-01-20 18:51:58

标签: c++

给出一个字符串:

std::string foo = "world->units.all[0]";

如何将foo表示的值传递给函数? :

bar(foo);        // Passing the string
bar(magic(foo)); // Passing world->units.all[0] (whatever that is)

注意:字符串foo是用户输入的,但是我不会担心用户会把自己搞砸,因为它都是本地的。被访问的结构是结构,类,数组和指针。

2 个答案:

答案 0 :(得分:1)

本机无法在C ++中执行此操作。它没有运行时解析器或解释器。要做到这一点,你将不得不实现这两个。

答案 1 :(得分:0)

您可以使用地图来访问所需的值。

std::string foo = "world->units.all[0]";
std::map<std::string, std::string*> world_map;

void init()
{
  world_map[foo] = &world->units.all[0];
}

std::string magic(const std::string &foo)
{
  return *world_map[foo];
}