只要您不介意一些限制,这相当容易做到。完成这项工作的最简单方法是将您限制为从一个公共基类派生的类。在这种情况下,您可以执行以下操作:
// warning: I've done this before, but none of this code is tested. The idea
// of the code works, but this probably has at least a few typos and such.
struct functor_base {
virtual bool operator()() = 0;
};
然后,您显然需要一些从该基础派生的具体类:
struct eval_x : functor_base {
virtual bool operator()() { std::cout << "eval_x"; }
};
struct eval_y : functor_base {
virtual bool operator()() { std::cout << "eval_y"; }
};
然后我们需要某种方法来创建每种类型的对象:
functor_base *create_eval_x() { return new eval_x; }
functor_base *create_eval_y() { return new eval_y; }
最后,我们需要一个从名称到工厂函数的映射:
// the second template parameter is:
// pointer to function returning `functor_base *` and taking no parameters.
std::map<std::string, functor_base *(*)()> name_mapper;
name_mapper["eval_x"] = create_eval_x;
name_mapper["eval_y"] = create_eval_y;
这(终于!)为我们提供了足够的信息,以便我们可以从名称映射到函数对象:
char *name = "eval_x";
// the map holds pointers to functions, so we need to invoke what it returns
// to get a pointer to a functor:
functor_base *b = name_mapper.find(name)();
// now we can execute the functor:
(*b)();
// since the object was created dynamically, we need to delete it when we're done:
delete b;
当然,总体主题有很多变化。例如,您可以静态创建每个对象的实例,然后将静态对象的地址放入映射中,而不是动态创建对象的工厂函数。