我有以下工厂功能:
std::auto_ptr<IPath> PathFactory(std::string const& branch_type, CPathModel const& path_model)
{
using namespace boost::assign;
using namespace boost::phoenix::placeholders;
typedef boost::function<IPath* (CPathModel const&)> PathFactoryFunction;
typedef boost::unordered_map<std::string, PathFactoryFunction> FactoryMap;
static FactoryMap factory_map = map_list_of<std::string, PathFactoryFunction>
("plu", &phx::new_<CPluPath>)
("time_of_day", &phx::new_<CTimeOfDayPath>)
("probability", &phx::new_<CProbabilityPath>)
;
std::auto_ptr<IPath> new_path;
FactoryMap::const_iterator it = factory_map.find(branch_type);
if (it != factory_map.end())
{
new_path.reset(it->second(path_model));
}
return new_path;
}
此代码无法编译,请注意我使用的是 C++03。我在这里尝试做的是创建字符串到可以分配特定类型对象的小函数对象的映射。每个对象都有一个相同类型的构造参数 ( CPathModel const&
)。
phx::new_
有几个重载,所以直接引用它可能不是最好的主意,但我希望每个人都可以帮助我找到一种方法来使用 boost::phoenix 来清理这段代码并使映射工作优雅。
在这一点上,似乎更容易定义一个带有重载()
运算符的小型模板类,该运算符接受参数并在new T(p1)
内部执行。但这是样板文件,看起来很简单,提升必须在某个地方有一个很好的解决方案......