1

我有以下工厂功能:

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)内部执行。但这是样板文件,看起来很简单,提升必须在某个地方有一个很好的解决方案......

4

1 回答 1

1

Phoenix 是惰性函子的实用程序。

这里不需要(看不到表达式模板)。

因此,您可以制作自己的工厂方法模板:

template <typename PathType> IPath* make_path(CPathModel const& model) { 
    return new PathType(model);
}

并使用它:

static FactoryMap factory_map = map_list_of<std::string, PathFactoryFunction>
  ("plu",           &make_path<CPluPath>)
  ("time_of_day",   &make_path<CTimeOfDayPath>)
  ("probability",   &make_path<CProbabilityPath>)
  ;

任务完成。

虽然,在这一点上,使用地图查找工厂的好处是零。事实上,这只是浪费。一个简单的开关[1]好得多。更重要的是,因为它删除了std::function.

[1]实际上,它需要被chained ifs,或者你可以打开一个Perfect Hash

于 2014-03-12T17:00:44.367 回答