助推凤凰地图new_
map of boost phoenix new_?
我有以下工厂函数:
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)
。但这是样板文件,似乎足够简单,boost必须有一个很好的解决方案… 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]将far优越。更重要的是,它删除了std::function
中的类型擦除(隐式虚拟多态性)。
[1]实际上,它需要链接if
s,或者您可以打开完美散列
相关文章:
- 为什么不;名字在地图上是按顺序排列的吗
- 基于多个条件处理地图中的所有元素
- 在C++中将矢量转换为嵌套地图
- 如果"new int"返回"int*",那么为什么"new int[n]"不返回"int**"?
- 有没有一种方法可以使用placement new将堆叠对象分配给分配的内存
- 重载运算符new[]的行为取决于析构函数
- 过载'operator new'如何导致无限循环?
- 创建具有 new in 函数和"this is nullptr"异常的对象
- Codelite C++ new project
- 在类c++中使用new声明数组
- g++用户定义的动态链接库上的全局new和delete运算符
- 替换基于地图的所有引用
- 如何区分地图中的 0 和 false?
- 地图计数确实很重要,或者只是检查是否存在
- 如何从地图中删除矢量对象
- 是否有任何C++功能可以对地图进行排序?
- 如何使用 std::variant 打印地图键/值?
- 如果整个应用程序是虚拟映射的,为什么 new 会进行系统调用?
- 从矢量或地图中删除共享指针
- 在 c++ 中,有一种方法可以创建一个包含地图作为值的树状地图?