如何将我自己的类对象从 boost 插入到 ptr_map 中。这些对象是模板化的,所以我不能在 map 中使用一些静态类型名称。所以我做了:
ptr_map<string, any> someMap;
我的类继承了boost::noncopyable。
someMap.insert("Test", new MyClass<SomeTemplate>());
错误是:错误:没有匹配函数来调用‘boost::ptr_map
。
更新: 我宁愿制作一些包装器并且不使用 boost::any。所以:
class IWrapper { };
class MyClass : public IWrapper { };
ptr_map<string, IWrapper> someMap;
someMap.insert("Test", new MyClass<SomeTemplate>());
为什么它不起作用(同样的错误)?我可以将继承的类传递给父接口(interface)。怎么了?
最佳答案
到目前为止,大多数此类问题都应该使用公共(public)基类来解决。当所有的类都将被类似地使用时就是这种情况。运行时多态性。
我看到了不允许使用公共(public)基类的正当理由。在这种情况下,boost::variant
通常会提供更好的服务,因为仍然有一些方法可以统一对待每个项目(访问者)。编译时多态性。
我从未见过 for boost::any
的合法用途。我并不是说没有,但它非常罕见,我从未遇到过。
也就是说,试试这个。
std::map<std::string,boost::any> someMap;
boost::any insanity = new MyClass<SomeTemplate>;
someMap.insert("Test",insanity);
或
boost::ptr_map<std::string,boost::any> someMap;
boost::any* ive_lost_it = new boost::any( new MyClass<SomeTemplate> );
someMap.insert("Test", ive_lost_it );
关于c++ - boost 任何使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3062739/