如果我有一个称为 Base 的多态基类以及从 Base 继承的 Derived1 和 Derived2 类。然后我可以使用 boost::lambda 创建一个工厂。就像是:
typedef boost::function<Base *()> Creator;
std::map<std::string,Creator> map1;
map1["Derived1"] = boost::lambda::new_ptr<Derived1>();
map1["Derived2"] = boost::lambda::new_ptr<Derived2>();
(这不是真正的代码,我只是想说明问题。)
这可行,因此我可以使用字符串在地图中进行查找,然后调用 lambda 函数来实例化该类。都好。
问题在于它处理的是原始指针,我更喜欢使用智能指针(std::shared_ptr)。
所以如果我改变:
typedef boost::function<Base *>() Creator;
至:
typedef boost::function<std::shared_ptr<Base> >() Creator;
然后我从这里被卡住了。我尝试将 boost::lambda::bind 与 boost::lambda::new_ptr 结合使用,但我运气不佳,无法克服编译错误。(大量与模板相关的错误输出。)
我在 StackOverflow 中检查了其他类似的消息,使用 boost::bind 和 boost::lambda::new_ptr 返回 shared_ptr 构造函数是关闭的,但是如果我尝试应用它的解决方案,我会得到上面提到的模板错误。
如果有帮助,我很乐意提供示例代码和实际错误,但希望上述信息就足够了。我在 GCC 4.6 上使用 boost 1.47.0 以及在 Fedora 15 上使用 4.7 快照。